blob: 2b08ab59f87b6fce6080d414537d0f43561af8e0 [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>
34
35#include <cutils/properties.h>
36
37#include <media/AudioTrack.h>
38#include <media/AudioRecord.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080039#include <media/IMediaPlayerService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040
41#include <private/media/AudioTrackShared.h>
42#include <private/media/AudioEffectShared.h>
43#include <hardware_legacy/AudioHardwareInterface.h>
44
45#include "AudioMixer.h"
46#include "AudioFlinger.h"
47
48#ifdef WITH_A2DP
49#include "A2dpAudioInterface.h"
50#endif
51
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <media/EffectsFactoryApi.h>
53#include <media/EffectVisualizerApi.h>
54
55// ----------------------------------------------------------------------------
56// the sim build doesn't have gettid
57
58#ifndef HAVE_GETTID
59# define gettid getpid
60#endif
61
62// ----------------------------------------------------------------------------
63
Eric Laurentde070132010-07-13 04:45:46 -070064extern const char * const gEffectLibPath;
65
Mathias Agopian65ab4712010-07-14 17:59:35 -070066namespace android {
67
68static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
69static const char* kHardwareLockedString = "Hardware lock is taken\n";
70
71//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
72static const float MAX_GAIN = 4096.0f;
73static const float MAX_GAIN_INT = 0x1000;
74
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
79// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
83
84static const int kDumpLockRetries = 50;
85static const int kDumpLockSleep = 20000;
86
87static const nsecs_t kWarningThrottle = seconds(5);
88
89
90#define AUDIOFLINGER_SECURITY_ENABLED 1
91
92// ----------------------------------------------------------------------------
93
94static bool recordingAllowed() {
95#ifndef HAVE_ANDROID_OS
96 return true;
97#endif
98#if AUDIOFLINGER_SECURITY_ENABLED
99 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
100 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
101 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
102 return ok;
103#else
104 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
105 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
106 return true;
107#endif
108}
109
110static bool settingsAllowed() {
111#ifndef HAVE_ANDROID_OS
112 return true;
113#endif
114#if AUDIOFLINGER_SECURITY_ENABLED
115 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
116 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
117 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
118 return ok;
119#else
120 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
121 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
122 return true;
123#endif
124}
125
Gloria Wang9ee159b2011-02-24 14:51:45 -0800126// To collect the amplifier usage
127static void addBatteryData(uint32_t params) {
128 sp<IBinder> binder =
129 defaultServiceManager()->getService(String16("media.player"));
130 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
131 if (service.get() == NULL) {
132 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
133 return;
134 }
135
136 service->addBatteryData(params);
137}
138
Mathias Agopian65ab4712010-07-14 17:59:35 -0700139// ----------------------------------------------------------------------------
140
141AudioFlinger::AudioFlinger()
142 : BnAudioFlinger(),
Eric Laurentde070132010-07-13 04:45:46 -0700143 mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700144{
Eric Laurent93575202011-01-18 18:39:02 -0800145 Mutex::Autolock _l(mLock);
146
Mathias Agopian65ab4712010-07-14 17:59:35 -0700147 mHardwareStatus = AUDIO_HW_IDLE;
148
149 mAudioHardware = AudioHardwareInterface::create();
150
151 mHardwareStatus = AUDIO_HW_INIT;
152 if (mAudioHardware->initCheck() == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800153 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700154 mMode = AudioSystem::MODE_NORMAL;
Eric Laurent93575202011-01-18 18:39:02 -0800155 mHardwareStatus = AUDIO_HW_SET_MODE;
156 mAudioHardware->setMode(mMode);
157 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
158 mAudioHardware->setMasterVolume(1.0f);
159 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700160 } else {
161 LOGE("Couldn't even initialize the stubbed audio hardware!");
162 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700163}
164
165AudioFlinger::~AudioFlinger()
166{
167 while (!mRecordThreads.isEmpty()) {
168 // closeInput() will remove first entry from mRecordThreads
169 closeInput(mRecordThreads.keyAt(0));
170 }
171 while (!mPlaybackThreads.isEmpty()) {
172 // closeOutput() will remove first entry from mPlaybackThreads
173 closeOutput(mPlaybackThreads.keyAt(0));
174 }
175 if (mAudioHardware) {
176 delete mAudioHardware;
177 }
178}
179
180
181
182status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
183{
184 const size_t SIZE = 256;
185 char buffer[SIZE];
186 String8 result;
187
188 result.append("Clients:\n");
189 for (size_t i = 0; i < mClients.size(); ++i) {
190 wp<Client> wClient = mClients.valueAt(i);
191 if (wClient != 0) {
192 sp<Client> client = wClient.promote();
193 if (client != 0) {
194 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
195 result.append(buffer);
196 }
197 }
198 }
199 write(fd, result.string(), result.size());
200 return NO_ERROR;
201}
202
203
204status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
205{
206 const size_t SIZE = 256;
207 char buffer[SIZE];
208 String8 result;
209 int hardwareStatus = mHardwareStatus;
210
211 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
212 result.append(buffer);
213 write(fd, result.string(), result.size());
214 return NO_ERROR;
215}
216
217status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
218{
219 const size_t SIZE = 256;
220 char buffer[SIZE];
221 String8 result;
222 snprintf(buffer, SIZE, "Permission Denial: "
223 "can't dump AudioFlinger from pid=%d, uid=%d\n",
224 IPCThreadState::self()->getCallingPid(),
225 IPCThreadState::self()->getCallingUid());
226 result.append(buffer);
227 write(fd, result.string(), result.size());
228 return NO_ERROR;
229}
230
231static bool tryLock(Mutex& mutex)
232{
233 bool locked = false;
234 for (int i = 0; i < kDumpLockRetries; ++i) {
235 if (mutex.tryLock() == NO_ERROR) {
236 locked = true;
237 break;
238 }
239 usleep(kDumpLockSleep);
240 }
241 return locked;
242}
243
244status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
245{
246 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
247 dumpPermissionDenial(fd, args);
248 } else {
249 // get state of hardware lock
250 bool hardwareLocked = tryLock(mHardwareLock);
251 if (!hardwareLocked) {
252 String8 result(kHardwareLockedString);
253 write(fd, result.string(), result.size());
254 } else {
255 mHardwareLock.unlock();
256 }
257
258 bool locked = tryLock(mLock);
259
260 // failed to lock - AudioFlinger is probably deadlocked
261 if (!locked) {
262 String8 result(kDeadlockedString);
263 write(fd, result.string(), result.size());
264 }
265
266 dumpClients(fd, args);
267 dumpInternals(fd, args);
268
269 // dump playback threads
270 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
271 mPlaybackThreads.valueAt(i)->dump(fd, args);
272 }
273
274 // dump record threads
275 for (size_t i = 0; i < mRecordThreads.size(); i++) {
276 mRecordThreads.valueAt(i)->dump(fd, args);
277 }
278
279 if (mAudioHardware) {
280 mAudioHardware->dumpState(fd, args);
281 }
282 if (locked) mLock.unlock();
283 }
284 return NO_ERROR;
285}
286
287
288// IAudioFlinger interface
289
290
291sp<IAudioTrack> AudioFlinger::createTrack(
292 pid_t pid,
293 int streamType,
294 uint32_t sampleRate,
295 int format,
296 int channelCount,
297 int frameCount,
298 uint32_t flags,
299 const sp<IMemory>& sharedBuffer,
300 int output,
301 int *sessionId,
302 status_t *status)
303{
304 sp<PlaybackThread::Track> track;
305 sp<TrackHandle> trackHandle;
306 sp<Client> client;
307 wp<Client> wclient;
308 status_t lStatus;
309 int lSessionId;
310
311 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
312 LOGE("invalid stream type");
313 lStatus = BAD_VALUE;
314 goto Exit;
315 }
316
317 {
318 Mutex::Autolock _l(mLock);
319 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700320 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700321 if (thread == NULL) {
322 LOGE("unknown output thread");
323 lStatus = BAD_VALUE;
324 goto Exit;
325 }
326
327 wclient = mClients.valueFor(pid);
328
329 if (wclient != NULL) {
330 client = wclient.promote();
331 } else {
332 client = new Client(this, pid);
333 mClients.add(pid, client);
334 }
335
Mathias Agopian65ab4712010-07-14 17:59:35 -0700336 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Eric Laurentde070132010-07-13 04:45:46 -0700337 if (sessionId != NULL && *sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700338 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700339 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
340 if (mPlaybackThreads.keyAt(i) != output) {
341 // prevent same audio session on different output threads
342 uint32_t sessions = t->hasAudioSession(*sessionId);
343 if (sessions & PlaybackThread::TRACK_SESSION) {
344 lStatus = BAD_VALUE;
345 goto Exit;
346 }
347 // check if an effect with same session ID is waiting for a track to be created
348 if (sessions & PlaybackThread::EFFECT_SESSION) {
349 effectThread = t.get();
350 }
Eric Laurentde070132010-07-13 04:45:46 -0700351 }
352 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700353 lSessionId = *sessionId;
354 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700355 // if no audio session id is provided, create one here
Eric Laurentf5aafb22010-11-18 08:40:16 -0800356 lSessionId = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700357 if (sessionId != NULL) {
358 *sessionId = lSessionId;
359 }
360 }
361 LOGV("createTrack() lSessionId: %d", lSessionId);
362
363 track = thread->createTrack_l(client, streamType, sampleRate, format,
364 channelCount, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700365
366 // move effect chain to this output thread if an effect on same session was waiting
367 // for a track to be created
368 if (lStatus == NO_ERROR && effectThread != NULL) {
369 Mutex::Autolock _dl(thread->mLock);
370 Mutex::Autolock _sl(effectThread->mLock);
371 moveEffectChain_l(lSessionId, effectThread, thread, true);
372 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700373 }
374 if (lStatus == NO_ERROR) {
375 trackHandle = new TrackHandle(track);
376 } else {
377 // remove local strong reference to Client before deleting the Track so that the Client
378 // destructor is called by the TrackBase destructor with mLock held
379 client.clear();
380 track.clear();
381 }
382
383Exit:
384 if(status) {
385 *status = lStatus;
386 }
387 return trackHandle;
388}
389
390uint32_t AudioFlinger::sampleRate(int output) const
391{
392 Mutex::Autolock _l(mLock);
393 PlaybackThread *thread = checkPlaybackThread_l(output);
394 if (thread == NULL) {
395 LOGW("sampleRate() unknown thread %d", output);
396 return 0;
397 }
398 return thread->sampleRate();
399}
400
401int AudioFlinger::channelCount(int output) const
402{
403 Mutex::Autolock _l(mLock);
404 PlaybackThread *thread = checkPlaybackThread_l(output);
405 if (thread == NULL) {
406 LOGW("channelCount() unknown thread %d", output);
407 return 0;
408 }
409 return thread->channelCount();
410}
411
412int AudioFlinger::format(int output) const
413{
414 Mutex::Autolock _l(mLock);
415 PlaybackThread *thread = checkPlaybackThread_l(output);
416 if (thread == NULL) {
417 LOGW("format() unknown thread %d", output);
418 return 0;
419 }
420 return thread->format();
421}
422
423size_t AudioFlinger::frameCount(int output) const
424{
425 Mutex::Autolock _l(mLock);
426 PlaybackThread *thread = checkPlaybackThread_l(output);
427 if (thread == NULL) {
428 LOGW("frameCount() unknown thread %d", output);
429 return 0;
430 }
431 return thread->frameCount();
432}
433
434uint32_t AudioFlinger::latency(int output) const
435{
436 Mutex::Autolock _l(mLock);
437 PlaybackThread *thread = checkPlaybackThread_l(output);
438 if (thread == NULL) {
439 LOGW("latency() unknown thread %d", output);
440 return 0;
441 }
442 return thread->latency();
443}
444
445status_t AudioFlinger::setMasterVolume(float value)
446{
447 // check calling permissions
448 if (!settingsAllowed()) {
449 return PERMISSION_DENIED;
450 }
451
452 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800453 { // scope for the lock
454 AutoMutex lock(mHardwareLock);
455 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
456 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
457 value = 1.0f;
458 }
459 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700460 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461
Eric Laurent93575202011-01-18 18:39:02 -0800462 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700463 mMasterVolume = value;
464 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
465 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
466
467 return NO_ERROR;
468}
469
470status_t AudioFlinger::setMode(int mode)
471{
472 status_t ret;
473
474 // check calling permissions
475 if (!settingsAllowed()) {
476 return PERMISSION_DENIED;
477 }
478 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
479 LOGW("Illegal value: setMode(%d)", mode);
480 return BAD_VALUE;
481 }
482
483 { // scope for the lock
484 AutoMutex lock(mHardwareLock);
485 mHardwareStatus = AUDIO_HW_SET_MODE;
486 ret = mAudioHardware->setMode(mode);
487 mHardwareStatus = AUDIO_HW_IDLE;
488 }
489
490 if (NO_ERROR == ret) {
491 Mutex::Autolock _l(mLock);
492 mMode = mode;
493 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
494 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495 }
496
497 return ret;
498}
499
500status_t AudioFlinger::setMicMute(bool state)
501{
502 // check calling permissions
503 if (!settingsAllowed()) {
504 return PERMISSION_DENIED;
505 }
506
507 AutoMutex lock(mHardwareLock);
508 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
509 status_t ret = mAudioHardware->setMicMute(state);
510 mHardwareStatus = AUDIO_HW_IDLE;
511 return ret;
512}
513
514bool AudioFlinger::getMicMute() const
515{
516 bool state = AudioSystem::MODE_INVALID;
517 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
518 mAudioHardware->getMicMute(&state);
519 mHardwareStatus = AUDIO_HW_IDLE;
520 return state;
521}
522
523status_t AudioFlinger::setMasterMute(bool muted)
524{
525 // check calling permissions
526 if (!settingsAllowed()) {
527 return PERMISSION_DENIED;
528 }
529
Eric Laurent93575202011-01-18 18:39:02 -0800530 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700531 mMasterMute = muted;
532 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
533 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
534
535 return NO_ERROR;
536}
537
538float AudioFlinger::masterVolume() const
539{
540 return mMasterVolume;
541}
542
543bool AudioFlinger::masterMute() const
544{
545 return mMasterMute;
546}
547
548status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
549{
550 // check calling permissions
551 if (!settingsAllowed()) {
552 return PERMISSION_DENIED;
553 }
554
555 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
556 return BAD_VALUE;
557 }
558
559 AutoMutex lock(mLock);
560 PlaybackThread *thread = NULL;
561 if (output) {
562 thread = checkPlaybackThread_l(output);
563 if (thread == NULL) {
564 return BAD_VALUE;
565 }
566 }
567
568 mStreamTypes[stream].volume = value;
569
570 if (thread == NULL) {
571 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
572 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
573 }
574 } else {
575 thread->setStreamVolume(stream, value);
576 }
577
578 return NO_ERROR;
579}
580
581status_t AudioFlinger::setStreamMute(int stream, bool muted)
582{
583 // check calling permissions
584 if (!settingsAllowed()) {
585 return PERMISSION_DENIED;
586 }
587
588 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
589 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
590 return BAD_VALUE;
591 }
592
Eric Laurent93575202011-01-18 18:39:02 -0800593 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594 mStreamTypes[stream].mute = muted;
595 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
596 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
597
598 return NO_ERROR;
599}
600
601float AudioFlinger::streamVolume(int stream, int output) const
602{
603 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
604 return 0.0f;
605 }
606
607 AutoMutex lock(mLock);
608 float volume;
609 if (output) {
610 PlaybackThread *thread = checkPlaybackThread_l(output);
611 if (thread == NULL) {
612 return 0.0f;
613 }
614 volume = thread->streamVolume(stream);
615 } else {
616 volume = mStreamTypes[stream].volume;
617 }
618
619 return volume;
620}
621
622bool AudioFlinger::streamMute(int stream) const
623{
624 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
625 return true;
626 }
627
628 return mStreamTypes[stream].mute;
629}
630
Mathias Agopian65ab4712010-07-14 17:59:35 -0700631status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
632{
633 status_t result;
634
635 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
636 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
637 // check calling permissions
638 if (!settingsAllowed()) {
639 return PERMISSION_DENIED;
640 }
641
Mathias Agopian65ab4712010-07-14 17:59:35 -0700642 // ioHandle == 0 means the parameters are global to the audio hardware interface
643 if (ioHandle == 0) {
644 AutoMutex lock(mHardwareLock);
645 mHardwareStatus = AUDIO_SET_PARAMETER;
646 result = mAudioHardware->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700647 mHardwareStatus = AUDIO_HW_IDLE;
648 return result;
649 }
650
651 // hold a strong ref on thread in case closeOutput() or closeInput() is called
652 // and the thread is exited once the lock is released
653 sp<ThreadBase> thread;
654 {
655 Mutex::Autolock _l(mLock);
656 thread = checkPlaybackThread_l(ioHandle);
657 if (thread == NULL) {
658 thread = checkRecordThread_l(ioHandle);
659 }
660 }
661 if (thread != NULL) {
662 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700663 return result;
664 }
665 return BAD_VALUE;
666}
667
668String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
669{
670// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
671// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
672
673 if (ioHandle == 0) {
674 return mAudioHardware->getParameters(keys);
675 }
676
677 Mutex::Autolock _l(mLock);
678
679 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
680 if (playbackThread != NULL) {
681 return playbackThread->getParameters(keys);
682 }
683 RecordThread *recordThread = checkRecordThread_l(ioHandle);
684 if (recordThread != NULL) {
685 return recordThread->getParameters(keys);
686 }
687 return String8("");
688}
689
690size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
691{
692 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
693}
694
695unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
696{
697 if (ioHandle == 0) {
698 return 0;
699 }
700
701 Mutex::Autolock _l(mLock);
702
703 RecordThread *recordThread = checkRecordThread_l(ioHandle);
704 if (recordThread != NULL) {
705 return recordThread->getInputFramesLost();
706 }
707 return 0;
708}
709
710status_t AudioFlinger::setVoiceVolume(float value)
711{
712 // check calling permissions
713 if (!settingsAllowed()) {
714 return PERMISSION_DENIED;
715 }
716
717 AutoMutex lock(mHardwareLock);
718 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
719 status_t ret = mAudioHardware->setVoiceVolume(value);
720 mHardwareStatus = AUDIO_HW_IDLE;
721
722 return ret;
723}
724
725status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
726{
727 status_t status;
728
729 Mutex::Autolock _l(mLock);
730
731 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
732 if (playbackThread != NULL) {
733 return playbackThread->getRenderPosition(halFrames, dspFrames);
734 }
735
736 return BAD_VALUE;
737}
738
739void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
740{
741
742 Mutex::Autolock _l(mLock);
743
744 int pid = IPCThreadState::self()->getCallingPid();
745 if (mNotificationClients.indexOfKey(pid) < 0) {
746 sp<NotificationClient> notificationClient = new NotificationClient(this,
747 client,
748 pid);
749 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
750
751 mNotificationClients.add(pid, notificationClient);
752
753 sp<IBinder> binder = client->asBinder();
754 binder->linkToDeath(notificationClient);
755
756 // the config change is always sent from playback or record threads to avoid deadlock
757 // with AudioSystem::gLock
758 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
759 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
760 }
761
762 for (size_t i = 0; i < mRecordThreads.size(); i++) {
763 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
764 }
765 }
766}
767
768void AudioFlinger::removeNotificationClient(pid_t pid)
769{
770 Mutex::Autolock _l(mLock);
771
772 int index = mNotificationClients.indexOfKey(pid);
773 if (index >= 0) {
774 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
775 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700776 mNotificationClients.removeItem(pid);
777 }
778}
779
780// audioConfigChanged_l() must be called with AudioFlinger::mLock held
781void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
782{
783 size_t size = mNotificationClients.size();
784 for (size_t i = 0; i < size; i++) {
785 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
786 }
787}
788
789// removeClient_l() must be called with AudioFlinger::mLock held
790void AudioFlinger::removeClient_l(pid_t pid)
791{
792 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
793 mClients.removeItem(pid);
794}
795
796
797// ----------------------------------------------------------------------------
798
799AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
800 : Thread(false),
801 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
802 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false)
803{
804}
805
806AudioFlinger::ThreadBase::~ThreadBase()
807{
808 mParamCond.broadcast();
809 mNewParameters.clear();
810}
811
812void AudioFlinger::ThreadBase::exit()
813{
814 // keep a strong ref on ourself so that we wont get
815 // destroyed in the middle of requestExitAndWait()
816 sp <ThreadBase> strongMe = this;
817
818 LOGV("ThreadBase::exit");
819 {
820 AutoMutex lock(&mLock);
821 mExiting = true;
822 requestExit();
823 mWaitWorkCV.signal();
824 }
825 requestExitAndWait();
826}
827
828uint32_t AudioFlinger::ThreadBase::sampleRate() const
829{
830 return mSampleRate;
831}
832
833int AudioFlinger::ThreadBase::channelCount() const
834{
835 return (int)mChannelCount;
836}
837
838int AudioFlinger::ThreadBase::format() const
839{
840 return mFormat;
841}
842
843size_t AudioFlinger::ThreadBase::frameCount() const
844{
845 return mFrameCount;
846}
847
848status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
849{
850 status_t status;
851
852 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
853 Mutex::Autolock _l(mLock);
854
855 mNewParameters.add(keyValuePairs);
856 mWaitWorkCV.signal();
857 // wait condition with timeout in case the thread loop has exited
858 // before the request could be processed
859 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
860 status = mParamStatus;
861 mWaitWorkCV.signal();
862 } else {
863 status = TIMED_OUT;
864 }
865 return status;
866}
867
868void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
869{
870 Mutex::Autolock _l(mLock);
871 sendConfigEvent_l(event, param);
872}
873
874// sendConfigEvent_l() must be called with ThreadBase::mLock held
875void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
876{
877 ConfigEvent *configEvent = new ConfigEvent();
878 configEvent->mEvent = event;
879 configEvent->mParam = param;
880 mConfigEvents.add(configEvent);
881 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
882 mWaitWorkCV.signal();
883}
884
885void AudioFlinger::ThreadBase::processConfigEvents()
886{
887 mLock.lock();
888 while(!mConfigEvents.isEmpty()) {
889 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
890 ConfigEvent *configEvent = mConfigEvents[0];
891 mConfigEvents.removeAt(0);
892 // release mLock before locking AudioFlinger mLock: lock order is always
893 // AudioFlinger then ThreadBase to avoid cross deadlock
894 mLock.unlock();
895 mAudioFlinger->mLock.lock();
896 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
897 mAudioFlinger->mLock.unlock();
898 delete configEvent;
899 mLock.lock();
900 }
901 mLock.unlock();
902}
903
904status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
905{
906 const size_t SIZE = 256;
907 char buffer[SIZE];
908 String8 result;
909
910 bool locked = tryLock(mLock);
911 if (!locked) {
912 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
913 write(fd, buffer, strlen(buffer));
914 }
915
916 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
917 result.append(buffer);
918 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
919 result.append(buffer);
920 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
921 result.append(buffer);
922 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
923 result.append(buffer);
924 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
925 result.append(buffer);
926 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
927 result.append(buffer);
928
929 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
930 result.append(buffer);
931 result.append(" Index Command");
932 for (size_t i = 0; i < mNewParameters.size(); ++i) {
933 snprintf(buffer, SIZE, "\n %02d ", i);
934 result.append(buffer);
935 result.append(mNewParameters[i]);
936 }
937
938 snprintf(buffer, SIZE, "\n\nPending config events: \n");
939 result.append(buffer);
940 snprintf(buffer, SIZE, " Index event param\n");
941 result.append(buffer);
942 for (size_t i = 0; i < mConfigEvents.size(); i++) {
943 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
944 result.append(buffer);
945 }
946 result.append("\n");
947
948 write(fd, result.string(), result.size());
949
950 if (locked) {
951 mLock.unlock();
952 }
953 return NO_ERROR;
954}
955
956
957// ----------------------------------------------------------------------------
958
959AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
960 : ThreadBase(audioFlinger, id),
961 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
962 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
963 mDevice(device)
964{
965 readOutputParameters();
966
967 mMasterVolume = mAudioFlinger->masterVolume();
968 mMasterMute = mAudioFlinger->masterMute();
969
970 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
971 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
972 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
973 }
974}
975
976AudioFlinger::PlaybackThread::~PlaybackThread()
977{
978 delete [] mMixBuffer;
979}
980
981status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
982{
983 dumpInternals(fd, args);
984 dumpTracks(fd, args);
985 dumpEffectChains(fd, args);
986 return NO_ERROR;
987}
988
989status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
990{
991 const size_t SIZE = 256;
992 char buffer[SIZE];
993 String8 result;
994
995 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
996 result.append(buffer);
997 result.append(" Name Clien Typ Fmt Chn Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
998 for (size_t i = 0; i < mTracks.size(); ++i) {
999 sp<Track> track = mTracks[i];
1000 if (track != 0) {
1001 track->dump(buffer, SIZE);
1002 result.append(buffer);
1003 }
1004 }
1005
1006 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1007 result.append(buffer);
1008 result.append(" Name Clien Typ Fmt Chn Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
1009 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1010 wp<Track> wTrack = mActiveTracks[i];
1011 if (wTrack != 0) {
1012 sp<Track> track = wTrack.promote();
1013 if (track != 0) {
1014 track->dump(buffer, SIZE);
1015 result.append(buffer);
1016 }
1017 }
1018 }
1019 write(fd, result.string(), result.size());
1020 return NO_ERROR;
1021}
1022
1023status_t AudioFlinger::PlaybackThread::dumpEffectChains(int fd, const Vector<String16>& args)
1024{
1025 const size_t SIZE = 256;
1026 char buffer[SIZE];
1027 String8 result;
1028
1029 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1030 write(fd, buffer, strlen(buffer));
1031
1032 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1033 sp<EffectChain> chain = mEffectChains[i];
1034 if (chain != 0) {
1035 chain->dump(fd, args);
1036 }
1037 }
1038 return NO_ERROR;
1039}
1040
1041status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1042{
1043 const size_t SIZE = 256;
1044 char buffer[SIZE];
1045 String8 result;
1046
1047 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1048 result.append(buffer);
1049 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1050 result.append(buffer);
1051 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1052 result.append(buffer);
1053 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1054 result.append(buffer);
1055 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1056 result.append(buffer);
1057 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1058 result.append(buffer);
1059 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1060 result.append(buffer);
1061 write(fd, result.string(), result.size());
1062
1063 dumpBase(fd, args);
1064
1065 return NO_ERROR;
1066}
1067
1068// Thread virtuals
1069status_t AudioFlinger::PlaybackThread::readyToRun()
1070{
1071 if (mSampleRate == 0) {
1072 LOGE("No working audio driver found.");
1073 return NO_INIT;
1074 }
1075 LOGI("AudioFlinger's thread %p ready to run", this);
1076 return NO_ERROR;
1077}
1078
1079void AudioFlinger::PlaybackThread::onFirstRef()
1080{
1081 const size_t SIZE = 256;
1082 char buffer[SIZE];
1083
1084 snprintf(buffer, SIZE, "Playback Thread %p", this);
1085
1086 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1087}
1088
1089// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1090sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1091 const sp<AudioFlinger::Client>& client,
1092 int streamType,
1093 uint32_t sampleRate,
1094 int format,
1095 int channelCount,
1096 int frameCount,
1097 const sp<IMemory>& sharedBuffer,
1098 int sessionId,
1099 status_t *status)
1100{
1101 sp<Track> track;
1102 status_t lStatus;
1103
1104 if (mType == DIRECT) {
1105 if (sampleRate != mSampleRate || format != mFormat || channelCount != (int)mChannelCount) {
1106 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
1107 sampleRate, format, channelCount, mOutput);
1108 lStatus = BAD_VALUE;
1109 goto Exit;
1110 }
1111 } else {
1112 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1113 if (sampleRate > mSampleRate*2) {
1114 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1115 lStatus = BAD_VALUE;
1116 goto Exit;
1117 }
1118 }
1119
1120 if (mOutput == 0) {
1121 LOGE("Audio driver not initialized.");
1122 lStatus = NO_INIT;
1123 goto Exit;
1124 }
1125
1126 { // scope for mLock
1127 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001128
1129 // all tracks in same audio session must share the same routing strategy otherwise
1130 // conflicts will happen when tracks are moved from one output to another by audio policy
1131 // manager
1132 uint32_t strategy =
1133 AudioSystem::getStrategyForStream((AudioSystem::stream_type)streamType);
1134 for (size_t i = 0; i < mTracks.size(); ++i) {
1135 sp<Track> t = mTracks[i];
1136 if (t != 0) {
1137 if (sessionId == t->sessionId() &&
1138 strategy != AudioSystem::getStrategyForStream((AudioSystem::stream_type)t->type())) {
1139 lStatus = BAD_VALUE;
1140 goto Exit;
1141 }
1142 }
1143 }
1144
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145 track = new Track(this, client, streamType, sampleRate, format,
1146 channelCount, frameCount, sharedBuffer, sessionId);
1147 if (track->getCblk() == NULL || track->name() < 0) {
1148 lStatus = NO_MEMORY;
1149 goto Exit;
1150 }
1151 mTracks.add(track);
1152
1153 sp<EffectChain> chain = getEffectChain_l(sessionId);
1154 if (chain != 0) {
1155 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1156 track->setMainBuffer(chain->inBuffer());
Eric Laurentde070132010-07-13 04:45:46 -07001157 chain->setStrategy(AudioSystem::getStrategyForStream((AudioSystem::stream_type)track->type()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001158 }
1159 }
1160 lStatus = NO_ERROR;
1161
1162Exit:
1163 if(status) {
1164 *status = lStatus;
1165 }
1166 return track;
1167}
1168
1169uint32_t AudioFlinger::PlaybackThread::latency() const
1170{
1171 if (mOutput) {
1172 return mOutput->latency();
1173 }
1174 else {
1175 return 0;
1176 }
1177}
1178
1179status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1180{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001181 mMasterVolume = value;
1182 return NO_ERROR;
1183}
1184
1185status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1186{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001187 mMasterMute = muted;
1188 return NO_ERROR;
1189}
1190
1191float AudioFlinger::PlaybackThread::masterVolume() const
1192{
1193 return mMasterVolume;
1194}
1195
1196bool AudioFlinger::PlaybackThread::masterMute() const
1197{
1198 return mMasterMute;
1199}
1200
1201status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1202{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001203 mStreamTypes[stream].volume = value;
1204 return NO_ERROR;
1205}
1206
1207status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1208{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001209 mStreamTypes[stream].mute = muted;
1210 return NO_ERROR;
1211}
1212
1213float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1214{
1215 return mStreamTypes[stream].volume;
1216}
1217
1218bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1219{
1220 return mStreamTypes[stream].mute;
1221}
1222
Mathias Agopian65ab4712010-07-14 17:59:35 -07001223// addTrack_l() must be called with ThreadBase::mLock held
1224status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1225{
1226 status_t status = ALREADY_EXISTS;
1227
1228 // set retry count for buffer fill
1229 track->mRetryCount = kMaxTrackStartupRetries;
1230 if (mActiveTracks.indexOf(track) < 0) {
1231 // the track is newly added, make sure it fills up all its
1232 // buffers before playing. This is to ensure the client will
1233 // effectively get the latency it requested.
1234 track->mFillingUpStatus = Track::FS_FILLING;
1235 track->mResetDone = false;
1236 mActiveTracks.add(track);
1237 if (track->mainBuffer() != mMixBuffer) {
1238 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1239 if (chain != 0) {
1240 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1241 chain->startTrack();
1242 }
1243 }
1244
1245 status = NO_ERROR;
1246 }
1247
1248 LOGV("mWaitWorkCV.broadcast");
1249 mWaitWorkCV.broadcast();
1250
1251 return status;
1252}
1253
1254// destroyTrack_l() must be called with ThreadBase::mLock held
1255void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1256{
1257 track->mState = TrackBase::TERMINATED;
1258 if (mActiveTracks.indexOf(track) < 0) {
1259 mTracks.remove(track);
1260 deleteTrackName_l(track->name());
1261 }
1262}
1263
1264String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1265{
1266 return mOutput->getParameters(keys);
1267}
1268
1269// destroyTrack_l() must be called with AudioFlinger::mLock held
1270void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1271 AudioSystem::OutputDescriptor desc;
1272 void *param2 = 0;
1273
1274 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1275
1276 switch (event) {
1277 case AudioSystem::OUTPUT_OPENED:
1278 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1279 desc.channels = mChannels;
1280 desc.samplingRate = mSampleRate;
1281 desc.format = mFormat;
1282 desc.frameCount = mFrameCount;
1283 desc.latency = latency();
1284 param2 = &desc;
1285 break;
1286
1287 case AudioSystem::STREAM_CONFIG_CHANGED:
1288 param2 = &param;
1289 case AudioSystem::OUTPUT_CLOSED:
1290 default:
1291 break;
1292 }
1293 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1294}
1295
1296void AudioFlinger::PlaybackThread::readOutputParameters()
1297{
1298 mSampleRate = mOutput->sampleRate();
1299 mChannels = mOutput->channels();
1300 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
1301 mFormat = mOutput->format();
1302 mFrameSize = (uint16_t)mOutput->frameSize();
1303 mFrameCount = mOutput->bufferSize() / mFrameSize;
1304
1305 // FIXME - Current mixer implementation only supports stereo output: Always
1306 // Allocate a stereo buffer even if HW output is mono.
1307 if (mMixBuffer != NULL) delete[] mMixBuffer;
1308 mMixBuffer = new int16_t[mFrameCount * 2];
1309 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1310
Eric Laurentde070132010-07-13 04:45:46 -07001311 // force reconfiguration of effect chains and engines to take new buffer size and audio
1312 // parameters into account
1313 // Note that mLock is not held when readOutputParameters() is called from the constructor
1314 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1315 // matter.
1316 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1317 Vector< sp<EffectChain> > effectChains = mEffectChains;
1318 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001319 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001320 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001321}
1322
1323status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1324{
1325 if (halFrames == 0 || dspFrames == 0) {
1326 return BAD_VALUE;
1327 }
1328 if (mOutput == 0) {
1329 return INVALID_OPERATION;
1330 }
1331 *halFrames = mBytesWritten/mOutput->frameSize();
1332
1333 return mOutput->getRenderPosition(dspFrames);
1334}
1335
Eric Laurent39e94f82010-07-28 01:32:47 -07001336uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001337{
1338 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001339 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001340 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001341 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001342 }
1343
1344 for (size_t i = 0; i < mTracks.size(); ++i) {
1345 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001346 if (sessionId == track->sessionId() &&
1347 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001348 result |= TRACK_SESSION;
1349 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001350 }
1351 }
1352
Eric Laurent39e94f82010-07-28 01:32:47 -07001353 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001354}
1355
Eric Laurentde070132010-07-13 04:45:46 -07001356uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1357{
1358 // session AudioSystem::SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1359 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1360 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX) {
1361 return AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
1362 }
1363 for (size_t i = 0; i < mTracks.size(); i++) {
1364 sp<Track> track = mTracks[i];
1365 if (sessionId == track->sessionId() &&
1366 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
1367 return AudioSystem::getStrategyForStream((AudioSystem::stream_type) track->type());
1368 }
1369 }
1370 return AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
1371}
1372
Mathias Agopian65ab4712010-07-14 17:59:35 -07001373sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain(int sessionId)
1374{
1375 Mutex::Autolock _l(mLock);
1376 return getEffectChain_l(sessionId);
1377}
1378
1379sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain_l(int sessionId)
1380{
1381 sp<EffectChain> chain;
1382
1383 size_t size = mEffectChains.size();
1384 for (size_t i = 0; i < size; i++) {
1385 if (mEffectChains[i]->sessionId() == sessionId) {
1386 chain = mEffectChains[i];
1387 break;
1388 }
1389 }
1390 return chain;
1391}
1392
1393void AudioFlinger::PlaybackThread::setMode(uint32_t mode)
1394{
1395 Mutex::Autolock _l(mLock);
1396 size_t size = mEffectChains.size();
1397 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07001398 mEffectChains[i]->setMode_l(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001399 }
1400}
1401
1402// ----------------------------------------------------------------------------
1403
1404AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1405 : PlaybackThread(audioFlinger, output, id, device),
1406 mAudioMixer(0)
1407{
1408 mType = PlaybackThread::MIXER;
1409 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1410
1411 // FIXME - Current mixer implementation only supports stereo output
1412 if (mChannelCount == 1) {
1413 LOGE("Invalid audio hardware channel count");
1414 }
1415}
1416
1417AudioFlinger::MixerThread::~MixerThread()
1418{
1419 delete mAudioMixer;
1420}
1421
1422bool AudioFlinger::MixerThread::threadLoop()
1423{
1424 Vector< sp<Track> > tracksToRemove;
1425 uint32_t mixerStatus = MIXER_IDLE;
1426 nsecs_t standbyTime = systemTime();
1427 size_t mixBufferSize = mFrameCount * mFrameSize;
1428 // FIXME: Relaxed timing because of a certain device that can't meet latency
1429 // Should be reduced to 2x after the vendor fixes the driver issue
1430 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1431 nsecs_t lastWarning = 0;
1432 bool longStandbyExit = false;
1433 uint32_t activeSleepTime = activeSleepTimeUs();
1434 uint32_t idleSleepTime = idleSleepTimeUs();
1435 uint32_t sleepTime = idleSleepTime;
1436 Vector< sp<EffectChain> > effectChains;
1437
1438 while (!exitPending())
1439 {
1440 processConfigEvents();
1441
1442 mixerStatus = MIXER_IDLE;
1443 { // scope for mLock
1444
1445 Mutex::Autolock _l(mLock);
1446
1447 if (checkForNewParameters_l()) {
1448 mixBufferSize = mFrameCount * mFrameSize;
1449 // FIXME: Relaxed timing because of a certain device that can't meet latency
1450 // Should be reduced to 2x after the vendor fixes the driver issue
1451 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1452 activeSleepTime = activeSleepTimeUs();
1453 idleSleepTime = idleSleepTimeUs();
1454 }
1455
1456 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1457
1458 // put audio hardware into standby after short delay
1459 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1460 mSuspended) {
1461 if (!mStandby) {
1462 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1463 mOutput->standby();
1464 mStandby = true;
1465 mBytesWritten = 0;
1466 }
1467
1468 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1469 // we're about to wait, flush the binder command buffer
1470 IPCThreadState::self()->flushCommands();
1471
1472 if (exitPending()) break;
1473
1474 // wait until we have something to do...
1475 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1476 mWaitWorkCV.wait(mLock);
1477 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1478
1479 if (mMasterMute == false) {
1480 char value[PROPERTY_VALUE_MAX];
1481 property_get("ro.audio.silent", value, "0");
1482 if (atoi(value)) {
1483 LOGD("Silence is golden");
1484 setMasterMute(true);
1485 }
1486 }
1487
1488 standbyTime = systemTime() + kStandbyTimeInNsecs;
1489 sleepTime = idleSleepTime;
1490 continue;
1491 }
1492 }
1493
1494 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1495
1496 // prevent any changes in effect chain list and in each effect chain
1497 // during mixing and effect process as the audio buffers could be deleted
1498 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001499 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001500 }
1501
1502 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1503 // mix buffers...
1504 mAudioMixer->process();
1505 sleepTime = 0;
1506 standbyTime = systemTime() + kStandbyTimeInNsecs;
1507 //TODO: delay standby when effects have a tail
1508 } else {
1509 // If no tracks are ready, sleep once for the duration of an output
1510 // buffer size, then write 0s to the output
1511 if (sleepTime == 0) {
1512 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1513 sleepTime = activeSleepTime;
1514 } else {
1515 sleepTime = idleSleepTime;
1516 }
1517 } else if (mBytesWritten != 0 ||
1518 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
1519 memset (mMixBuffer, 0, mixBufferSize);
1520 sleepTime = 0;
1521 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
1522 }
1523 // TODO add standby time extension fct of effect tail
1524 }
1525
1526 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07001527 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001528 }
1529 // sleepTime == 0 means we must write to audio hardware
1530 if (sleepTime == 0) {
1531 for (size_t i = 0; i < effectChains.size(); i ++) {
1532 effectChains[i]->process_l();
1533 }
1534 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001535 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536 mLastWriteTime = systemTime();
1537 mInWrite = true;
1538 mBytesWritten += mixBufferSize;
1539
1540 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
1541 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
1542 mNumWrites++;
1543 mInWrite = false;
1544 nsecs_t now = systemTime();
1545 nsecs_t delta = now - mLastWriteTime;
1546 if (delta > maxPeriod) {
1547 mNumDelayedWrites++;
1548 if ((now - lastWarning) > kWarningThrottle) {
1549 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1550 ns2ms(delta), mNumDelayedWrites, this);
1551 lastWarning = now;
1552 }
1553 if (mStandby) {
1554 longStandbyExit = true;
1555 }
1556 }
1557 mStandby = false;
1558 } else {
1559 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001560 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561 usleep(sleepTime);
1562 }
1563
1564 // finally let go of all our tracks, without the lock held
1565 // since we can't guarantee the destructors won't acquire that
1566 // same lock.
1567 tracksToRemove.clear();
1568
1569 // Effect chains will be actually deleted here if they were removed from
1570 // mEffectChains list during mixing or effects processing
1571 effectChains.clear();
1572 }
1573
1574 if (!mStandby) {
1575 mOutput->standby();
1576 }
1577
1578 LOGV("MixerThread %p exiting", this);
1579 return false;
1580}
1581
1582// prepareTracks_l() must be called with ThreadBase::mLock held
1583uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1584{
1585
1586 uint32_t mixerStatus = MIXER_IDLE;
1587 // find out which tracks need to be processed
1588 size_t count = activeTracks.size();
1589 size_t mixedTracks = 0;
1590 size_t tracksWithEffect = 0;
1591
1592 float masterVolume = mMasterVolume;
1593 bool masterMute = mMasterMute;
1594
Eric Laurent571d49c2010-08-11 05:20:11 -07001595 if (masterMute) {
1596 masterVolume = 0;
1597 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598 // Delegate master volume control to effect in output mix effect chain if needed
Eric Laurentde070132010-07-13 04:45:46 -07001599 sp<EffectChain> chain = getEffectChain_l(AudioSystem::SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07001601 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07001602 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603 masterVolume = (float)((v + (1 << 23)) >> 24);
1604 chain.clear();
1605 }
1606
1607 for (size_t i=0 ; i<count ; i++) {
1608 sp<Track> t = activeTracks[i].promote();
1609 if (t == 0) continue;
1610
1611 Track* const track = t.get();
1612 audio_track_cblk_t* cblk = track->cblk();
1613
1614 // The first time a track is added we wait
1615 // for all its buffers to be filled before processing it
1616 mAudioMixer->setActiveTrack(track->name());
Eric Laurentaf59ce22010-10-05 14:41:42 -07001617 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618 !track->isPaused() && !track->isTerminated())
1619 {
1620 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
1621
1622 mixedTracks++;
1623
1624 // track->mainBuffer() != mMixBuffer means there is an effect chain
1625 // connected to the track
1626 chain.clear();
1627 if (track->mainBuffer() != mMixBuffer) {
1628 chain = getEffectChain_l(track->sessionId());
1629 // Delegate volume control to effect in track effect chain if needed
1630 if (chain != 0) {
1631 tracksWithEffect++;
1632 } else {
1633 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1634 track->name(), track->sessionId());
1635 }
1636 }
1637
1638
1639 int param = AudioMixer::VOLUME;
1640 if (track->mFillingUpStatus == Track::FS_FILLED) {
1641 // no ramp for the first volume setting
1642 track->mFillingUpStatus = Track::FS_ACTIVE;
1643 if (track->mState == TrackBase::RESUMING) {
1644 track->mState = TrackBase::ACTIVE;
1645 param = AudioMixer::RAMP_VOLUME;
1646 }
Eric Laurent243f5f92011-02-28 16:52:51 -08001647 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001648 } else if (cblk->server != 0) {
1649 // If the track is stopped before the first frame was mixed,
1650 // do not apply ramp
1651 param = AudioMixer::RAMP_VOLUME;
1652 }
1653
1654 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07001655 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07001656 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07001658 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659 if (track->isPausing()) {
1660 track->setPaused();
1661 }
1662 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07001663
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 // read original volumes with volume control
1665 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07001667 vl = (uint32_t)(v * cblk->volume[0]) << 12;
1668 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001669
Eric Laurente0aed6d2010-09-10 17:44:44 -07001670 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07001672 // Delegate volume control to effect in track effect chain if needed
1673 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1674 // Do not ramp volume if volume is controlled by effect
1675 param = AudioMixer::VOLUME;
1676 track->mHasVolumeController = true;
1677 } else {
1678 // force no volume ramp when volume controller was just disabled or removed
1679 // from effect chain to avoid volume spike
1680 if (track->mHasVolumeController) {
1681 param = AudioMixer::VOLUME;
1682 }
1683 track->mHasVolumeController = false;
1684 }
1685
1686 // Convert volumes from 8.24 to 4.12 format
1687 int16_t left, right, aux;
1688 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1689 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1690 left = int16_t(v_clamped);
1691 v_clamped = (vr + (1 << 11)) >> 12;
1692 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1693 right = int16_t(v_clamped);
1694
1695 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
1696 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001697
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698 // XXX: these things DON'T need to be done each time
1699 mAudioMixer->setBufferProvider(track);
1700 mAudioMixer->enable(AudioMixer::MIXING);
1701
1702 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1703 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1704 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
1705 mAudioMixer->setParameter(
1706 AudioMixer::TRACK,
1707 AudioMixer::FORMAT, (void *)track->format());
1708 mAudioMixer->setParameter(
1709 AudioMixer::TRACK,
1710 AudioMixer::CHANNEL_COUNT, (void *)track->channelCount());
1711 mAudioMixer->setParameter(
1712 AudioMixer::RESAMPLE,
1713 AudioMixer::SAMPLE_RATE,
1714 (void *)(cblk->sampleRate));
1715 mAudioMixer->setParameter(
1716 AudioMixer::TRACK,
1717 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1718 mAudioMixer->setParameter(
1719 AudioMixer::TRACK,
1720 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
1721
1722 // reset retry count
1723 track->mRetryCount = kMaxTrackRetries;
1724 mixerStatus = MIXER_TRACKS_READY;
1725 } else {
1726 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
1727 if (track->isStopped()) {
1728 track->reset();
1729 }
1730 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1731 // We have consumed all the buffers of this track.
1732 // Remove it from the list of active tracks.
1733 tracksToRemove->add(track);
1734 } else {
1735 // No buffers for this track. Give it a few chances to
1736 // fill a buffer, then remove it from active list.
1737 if (--(track->mRetryCount) <= 0) {
1738 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
1739 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07001740 // indicate to client process that the track was disabled because of underrun
1741 cblk->flags |= CBLK_DISABLED_ON;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742 } else if (mixerStatus != MIXER_TRACKS_READY) {
1743 mixerStatus = MIXER_TRACKS_ENABLED;
1744 }
1745 }
1746 mAudioMixer->disable(AudioMixer::MIXING);
1747 }
1748 }
1749
1750 // remove all the tracks that need to be...
1751 count = tracksToRemove->size();
1752 if (UNLIKELY(count)) {
1753 for (size_t i=0 ; i<count ; i++) {
1754 const sp<Track>& track = tracksToRemove->itemAt(i);
1755 mActiveTracks.remove(track);
1756 if (track->mainBuffer() != mMixBuffer) {
1757 chain = getEffectChain_l(track->sessionId());
1758 if (chain != 0) {
1759 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
1760 chain->stopTrack();
1761 }
1762 }
1763 if (track->isTerminated()) {
1764 mTracks.remove(track);
1765 deleteTrackName_l(track->mName);
1766 }
1767 }
1768 }
1769
1770 // mix buffer must be cleared if all tracks are connected to an
1771 // effect chain as in this case the mixer will not write to
1772 // mix buffer and track effects will accumulate into it
1773 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1774 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1775 }
1776
1777 return mixerStatus;
1778}
1779
1780void AudioFlinger::MixerThread::invalidateTracks(int streamType)
1781{
Eric Laurentde070132010-07-13 04:45:46 -07001782 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1783 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001785
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786 size_t size = mTracks.size();
1787 for (size_t i = 0; i < size; i++) {
1788 sp<Track> t = mTracks[i];
1789 if (t->type() == streamType) {
1790 t->mCblk->lock.lock();
1791 t->mCblk->flags |= CBLK_INVALID_ON;
1792 t->mCblk->cv.signal();
1793 t->mCblk->lock.unlock();
1794 }
1795 }
1796}
1797
1798
1799// getTrackName_l() must be called with ThreadBase::mLock held
1800int AudioFlinger::MixerThread::getTrackName_l()
1801{
1802 return mAudioMixer->getTrackName();
1803}
1804
1805// deleteTrackName_l() must be called with ThreadBase::mLock held
1806void AudioFlinger::MixerThread::deleteTrackName_l(int name)
1807{
1808 LOGV("remove track (%d) and delete from mixer", name);
1809 mAudioMixer->deleteTrackName(name);
1810}
1811
1812// checkForNewParameters_l() must be called with ThreadBase::mLock held
1813bool AudioFlinger::MixerThread::checkForNewParameters_l()
1814{
1815 bool reconfig = false;
1816
1817 while (!mNewParameters.isEmpty()) {
1818 status_t status = NO_ERROR;
1819 String8 keyValuePair = mNewParameters[0];
1820 AudioParameter param = AudioParameter(keyValuePair);
1821 int value;
1822
1823 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1824 reconfig = true;
1825 }
1826 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1827 if (value != AudioSystem::PCM_16_BIT) {
1828 status = BAD_VALUE;
1829 } else {
1830 reconfig = true;
1831 }
1832 }
1833 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1834 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1835 status = BAD_VALUE;
1836 } else {
1837 reconfig = true;
1838 }
1839 }
1840 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1841 // do not accept frame count changes if tracks are open as the track buffer
1842 // size depends on frame count and correct behavior would not be garantied
1843 // if frame count is changed after track creation
1844 if (!mTracks.isEmpty()) {
1845 status = INVALID_OPERATION;
1846 } else {
1847 reconfig = true;
1848 }
1849 }
1850 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08001851 // when changing the audio output device, call addBatteryData to notify
1852 // the change
1853 if (mDevice != value) {
1854 uint32_t params = 0;
1855 // check whether speaker is on
1856 if (value & AudioSystem::DEVICE_OUT_SPEAKER) {
1857 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
1858 }
1859
1860 int deviceWithoutSpeaker
1861 = AudioSystem::DEVICE_OUT_ALL & ~AudioSystem::DEVICE_OUT_SPEAKER;
1862 // check if any other device (except speaker) is on
1863 if (value & deviceWithoutSpeaker ) {
1864 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
1865 }
1866
1867 if (params != 0) {
1868 addBatteryData(params);
1869 }
1870 }
1871
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872 // forward device change to effects that have requested to be
1873 // aware of attached audio device.
1874 mDevice = (uint32_t)value;
1875 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07001876 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877 }
1878 }
1879
1880 if (status == NO_ERROR) {
1881 status = mOutput->setParameters(keyValuePair);
1882 if (!mStandby && status == INVALID_OPERATION) {
1883 mOutput->standby();
1884 mStandby = true;
1885 mBytesWritten = 0;
1886 status = mOutput->setParameters(keyValuePair);
1887 }
1888 if (status == NO_ERROR && reconfig) {
1889 delete mAudioMixer;
1890 readOutputParameters();
1891 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1892 for (size_t i = 0; i < mTracks.size() ; i++) {
1893 int name = getTrackName_l();
1894 if (name < 0) break;
1895 mTracks[i]->mName = name;
1896 // limit track sample rate to 2 x new output sample rate
1897 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1898 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1899 }
1900 }
1901 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
1902 }
1903 }
1904
1905 mNewParameters.removeAt(0);
1906
1907 mParamStatus = status;
1908 mParamCond.signal();
1909 mWaitWorkCV.wait(mLock);
1910 }
1911 return reconfig;
1912}
1913
1914status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1915{
1916 const size_t SIZE = 256;
1917 char buffer[SIZE];
1918 String8 result;
1919
1920 PlaybackThread::dumpInternals(fd, args);
1921
1922 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1923 result.append(buffer);
1924 write(fd, result.string(), result.size());
1925 return NO_ERROR;
1926}
1927
1928uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
1929{
1930 return (uint32_t)(mOutput->latency() * 1000) / 2;
1931}
1932
1933uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
1934{
Eric Laurent60e18242010-07-29 06:50:24 -07001935 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936}
1937
Eric Laurent25cbe0e2010-08-18 18:13:17 -07001938uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
1939{
1940 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
1941}
1942
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943// ----------------------------------------------------------------------------
1944AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1945 : PlaybackThread(audioFlinger, output, id, device)
1946{
1947 mType = PlaybackThread::DIRECT;
1948}
1949
1950AudioFlinger::DirectOutputThread::~DirectOutputThread()
1951{
1952}
1953
1954
1955static inline int16_t clamp16(int32_t sample)
1956{
1957 if ((sample>>15) ^ (sample>>31))
1958 sample = 0x7FFF ^ (sample>>31);
1959 return sample;
1960}
1961
1962static inline
1963int32_t mul(int16_t in, int16_t v)
1964{
1965#if defined(__arm__) && !defined(__thumb__)
1966 int32_t out;
1967 asm( "smulbb %[out], %[in], %[v] \n"
1968 : [out]"=r"(out)
1969 : [in]"%r"(in), [v]"r"(v)
1970 : );
1971 return out;
1972#else
1973 return in * int32_t(v);
1974#endif
1975}
1976
1977void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
1978{
1979 // Do not apply volume on compressed audio
1980 if (!AudioSystem::isLinearPCM(mFormat)) {
1981 return;
1982 }
1983
1984 // convert to signed 16 bit before volume calculation
1985 if (mFormat == AudioSystem::PCM_8_BIT) {
1986 size_t count = mFrameCount * mChannelCount;
1987 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
1988 int16_t *dst = mMixBuffer + count-1;
1989 while(count--) {
1990 *dst-- = (int16_t)(*src--^0x80) << 8;
1991 }
1992 }
1993
1994 size_t frameCount = mFrameCount;
1995 int16_t *out = mMixBuffer;
1996 if (ramp) {
1997 if (mChannelCount == 1) {
1998 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
1999 int32_t vlInc = d / (int32_t)frameCount;
2000 int32_t vl = ((int32_t)mLeftVolShort << 16);
2001 do {
2002 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2003 out++;
2004 vl += vlInc;
2005 } while (--frameCount);
2006
2007 } else {
2008 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2009 int32_t vlInc = d / (int32_t)frameCount;
2010 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2011 int32_t vrInc = d / (int32_t)frameCount;
2012 int32_t vl = ((int32_t)mLeftVolShort << 16);
2013 int32_t vr = ((int32_t)mRightVolShort << 16);
2014 do {
2015 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2016 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2017 out += 2;
2018 vl += vlInc;
2019 vr += vrInc;
2020 } while (--frameCount);
2021 }
2022 } else {
2023 if (mChannelCount == 1) {
2024 do {
2025 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2026 out++;
2027 } while (--frameCount);
2028 } else {
2029 do {
2030 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2031 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2032 out += 2;
2033 } while (--frameCount);
2034 }
2035 }
2036
2037 // convert back to unsigned 8 bit after volume calculation
2038 if (mFormat == AudioSystem::PCM_8_BIT) {
2039 size_t count = mFrameCount * mChannelCount;
2040 int16_t *src = mMixBuffer;
2041 uint8_t *dst = (uint8_t *)mMixBuffer;
2042 while(count--) {
2043 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2044 }
2045 }
2046
2047 mLeftVolShort = leftVol;
2048 mRightVolShort = rightVol;
2049}
2050
2051bool AudioFlinger::DirectOutputThread::threadLoop()
2052{
2053 uint32_t mixerStatus = MIXER_IDLE;
2054 sp<Track> trackToRemove;
2055 sp<Track> activeTrack;
2056 nsecs_t standbyTime = systemTime();
2057 int8_t *curBuf;
2058 size_t mixBufferSize = mFrameCount*mFrameSize;
2059 uint32_t activeSleepTime = activeSleepTimeUs();
2060 uint32_t idleSleepTime = idleSleepTimeUs();
2061 uint32_t sleepTime = idleSleepTime;
2062 // use shorter standby delay as on normal output to release
2063 // hardware resources as soon as possible
2064 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2065
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066 while (!exitPending())
2067 {
2068 bool rampVolume;
2069 uint16_t leftVol;
2070 uint16_t rightVol;
2071 Vector< sp<EffectChain> > effectChains;
2072
2073 processConfigEvents();
2074
2075 mixerStatus = MIXER_IDLE;
2076
2077 { // scope for the mLock
2078
2079 Mutex::Autolock _l(mLock);
2080
2081 if (checkForNewParameters_l()) {
2082 mixBufferSize = mFrameCount*mFrameSize;
2083 activeSleepTime = activeSleepTimeUs();
2084 idleSleepTime = idleSleepTimeUs();
2085 standbyDelay = microseconds(activeSleepTime*2);
2086 }
2087
2088 // put audio hardware into standby after short delay
2089 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2090 mSuspended) {
2091 // wait until we have something to do...
2092 if (!mStandby) {
2093 LOGV("Audio hardware entering standby, mixer %p\n", this);
2094 mOutput->standby();
2095 mStandby = true;
2096 mBytesWritten = 0;
2097 }
2098
2099 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2100 // we're about to wait, flush the binder command buffer
2101 IPCThreadState::self()->flushCommands();
2102
2103 if (exitPending()) break;
2104
2105 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2106 mWaitWorkCV.wait(mLock);
2107 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2108
2109 if (mMasterMute == false) {
2110 char value[PROPERTY_VALUE_MAX];
2111 property_get("ro.audio.silent", value, "0");
2112 if (atoi(value)) {
2113 LOGD("Silence is golden");
2114 setMasterMute(true);
2115 }
2116 }
2117
2118 standbyTime = systemTime() + standbyDelay;
2119 sleepTime = idleSleepTime;
2120 continue;
2121 }
2122 }
2123
2124 effectChains = mEffectChains;
2125
2126 // find out which tracks need to be processed
2127 if (mActiveTracks.size() != 0) {
2128 sp<Track> t = mActiveTracks[0].promote();
2129 if (t == 0) continue;
2130
2131 Track* const track = t.get();
2132 audio_track_cblk_t* cblk = track->cblk();
2133
2134 // The first time a track is added we wait
2135 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002136 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137 !track->isPaused() && !track->isTerminated())
2138 {
2139 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2140
2141 if (track->mFillingUpStatus == Track::FS_FILLED) {
2142 track->mFillingUpStatus = Track::FS_ACTIVE;
2143 mLeftVolFloat = mRightVolFloat = 0;
2144 mLeftVolShort = mRightVolShort = 0;
2145 if (track->mState == TrackBase::RESUMING) {
2146 track->mState = TrackBase::ACTIVE;
2147 rampVolume = true;
2148 }
2149 } else if (cblk->server != 0) {
2150 // If the track is stopped before the first frame was mixed,
2151 // do not apply ramp
2152 rampVolume = true;
2153 }
2154 // compute volume for this track
2155 float left, right;
2156 if (track->isMuted() || mMasterMute || track->isPausing() ||
2157 mStreamTypes[track->type()].mute) {
2158 left = right = 0;
2159 if (track->isPausing()) {
2160 track->setPaused();
2161 }
2162 } else {
2163 float typeVolume = mStreamTypes[track->type()].volume;
2164 float v = mMasterVolume * typeVolume;
2165 float v_clamped = v * cblk->volume[0];
2166 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2167 left = v_clamped/MAX_GAIN;
2168 v_clamped = v * cblk->volume[1];
2169 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2170 right = v_clamped/MAX_GAIN;
2171 }
2172
2173 if (left != mLeftVolFloat || right != mRightVolFloat) {
2174 mLeftVolFloat = left;
2175 mRightVolFloat = right;
2176
2177 // If audio HAL implements volume control,
2178 // force software volume to nominal value
2179 if (mOutput->setVolume(left, right) == NO_ERROR) {
2180 left = 1.0f;
2181 right = 1.0f;
2182 }
2183
2184 // Convert volumes from float to 8.24
2185 uint32_t vl = (uint32_t)(left * (1 << 24));
2186 uint32_t vr = (uint32_t)(right * (1 << 24));
2187
2188 // Delegate volume control to effect in track effect chain if needed
2189 // only one effect chain can be present on DirectOutputThread, so if
2190 // there is one, the track is connected to it
2191 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002192 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002193 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194 rampVolume = false;
2195 }
2196 }
2197
2198 // Convert volumes from 8.24 to 4.12 format
2199 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2200 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2201 leftVol = (uint16_t)v_clamped;
2202 v_clamped = (vr + (1 << 11)) >> 12;
2203 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2204 rightVol = (uint16_t)v_clamped;
2205 } else {
2206 leftVol = mLeftVolShort;
2207 rightVol = mRightVolShort;
2208 rampVolume = false;
2209 }
2210
2211 // reset retry count
2212 track->mRetryCount = kMaxTrackRetriesDirect;
2213 activeTrack = t;
2214 mixerStatus = MIXER_TRACKS_READY;
2215 } else {
2216 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2217 if (track->isStopped()) {
2218 track->reset();
2219 }
2220 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2221 // We have consumed all the buffers of this track.
2222 // Remove it from the list of active tracks.
2223 trackToRemove = track;
2224 } else {
2225 // No buffers for this track. Give it a few chances to
2226 // fill a buffer, then remove it from active list.
2227 if (--(track->mRetryCount) <= 0) {
2228 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2229 trackToRemove = track;
2230 } else {
2231 mixerStatus = MIXER_TRACKS_ENABLED;
2232 }
2233 }
2234 }
2235 }
2236
2237 // remove all the tracks that need to be...
2238 if (UNLIKELY(trackToRemove != 0)) {
2239 mActiveTracks.remove(trackToRemove);
2240 if (!effectChains.isEmpty()) {
Eric Laurentde070132010-07-13 04:45:46 -07002241 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2242 trackToRemove->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002243 effectChains[0]->stopTrack();
2244 }
2245 if (trackToRemove->isTerminated()) {
2246 mTracks.remove(trackToRemove);
2247 deleteTrackName_l(trackToRemove->mName);
2248 }
2249 }
2250
Eric Laurentde070132010-07-13 04:45:46 -07002251 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252 }
2253
2254 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2255 AudioBufferProvider::Buffer buffer;
2256 size_t frameCount = mFrameCount;
2257 curBuf = (int8_t *)mMixBuffer;
2258 // output audio to hardware
2259 while (frameCount) {
2260 buffer.frameCount = frameCount;
2261 activeTrack->getNextBuffer(&buffer);
2262 if (UNLIKELY(buffer.raw == 0)) {
2263 memset(curBuf, 0, frameCount * mFrameSize);
2264 break;
2265 }
2266 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2267 frameCount -= buffer.frameCount;
2268 curBuf += buffer.frameCount * mFrameSize;
2269 activeTrack->releaseBuffer(&buffer);
2270 }
2271 sleepTime = 0;
2272 standbyTime = systemTime() + standbyDelay;
2273 } else {
2274 if (sleepTime == 0) {
2275 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2276 sleepTime = activeSleepTime;
2277 } else {
2278 sleepTime = idleSleepTime;
2279 }
2280 } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
2281 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2282 sleepTime = 0;
2283 }
2284 }
2285
2286 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002287 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002288 }
2289 // sleepTime == 0 means we must write to audio hardware
2290 if (sleepTime == 0) {
2291 if (mixerStatus == MIXER_TRACKS_READY) {
2292 applyVolume(leftVol, rightVol, rampVolume);
2293 }
2294 for (size_t i = 0; i < effectChains.size(); i ++) {
2295 effectChains[i]->process_l();
2296 }
Eric Laurentde070132010-07-13 04:45:46 -07002297 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002298
2299 mLastWriteTime = systemTime();
2300 mInWrite = true;
2301 mBytesWritten += mixBufferSize;
2302 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
2303 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2304 mNumWrites++;
2305 mInWrite = false;
2306 mStandby = false;
2307 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002308 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002309 usleep(sleepTime);
2310 }
2311
2312 // finally let go of removed track, without the lock held
2313 // since we can't guarantee the destructors won't acquire that
2314 // same lock.
2315 trackToRemove.clear();
2316 activeTrack.clear();
2317
2318 // Effect chains will be actually deleted here if they were removed from
2319 // mEffectChains list during mixing or effects processing
2320 effectChains.clear();
2321 }
2322
2323 if (!mStandby) {
2324 mOutput->standby();
2325 }
2326
2327 LOGV("DirectOutputThread %p exiting", this);
2328 return false;
2329}
2330
2331// getTrackName_l() must be called with ThreadBase::mLock held
2332int AudioFlinger::DirectOutputThread::getTrackName_l()
2333{
2334 return 0;
2335}
2336
2337// deleteTrackName_l() must be called with ThreadBase::mLock held
2338void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2339{
2340}
2341
2342// checkForNewParameters_l() must be called with ThreadBase::mLock held
2343bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2344{
2345 bool reconfig = false;
2346
2347 while (!mNewParameters.isEmpty()) {
2348 status_t status = NO_ERROR;
2349 String8 keyValuePair = mNewParameters[0];
2350 AudioParameter param = AudioParameter(keyValuePair);
2351 int value;
2352
2353 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2354 // do not accept frame count changes if tracks are open as the track buffer
2355 // size depends on frame count and correct behavior would not be garantied
2356 // if frame count is changed after track creation
2357 if (!mTracks.isEmpty()) {
2358 status = INVALID_OPERATION;
2359 } else {
2360 reconfig = true;
2361 }
2362 }
2363 if (status == NO_ERROR) {
2364 status = mOutput->setParameters(keyValuePair);
2365 if (!mStandby && status == INVALID_OPERATION) {
2366 mOutput->standby();
2367 mStandby = true;
2368 mBytesWritten = 0;
2369 status = mOutput->setParameters(keyValuePair);
2370 }
2371 if (status == NO_ERROR && reconfig) {
2372 readOutputParameters();
2373 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2374 }
2375 }
2376
2377 mNewParameters.removeAt(0);
2378
2379 mParamStatus = status;
2380 mParamCond.signal();
2381 mWaitWorkCV.wait(mLock);
2382 }
2383 return reconfig;
2384}
2385
2386uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2387{
2388 uint32_t time;
2389 if (AudioSystem::isLinearPCM(mFormat)) {
2390 time = (uint32_t)(mOutput->latency() * 1000) / 2;
2391 } else {
2392 time = 10000;
2393 }
2394 return time;
2395}
2396
2397uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2398{
2399 uint32_t time;
2400 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002401 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002402 } else {
2403 time = 10000;
2404 }
2405 return time;
2406}
2407
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002408uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2409{
2410 uint32_t time;
2411 if (AudioSystem::isLinearPCM(mFormat)) {
2412 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2413 } else {
2414 time = 10000;
2415 }
2416 return time;
2417}
2418
2419
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420// ----------------------------------------------------------------------------
2421
2422AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2423 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2424{
2425 mType = PlaybackThread::DUPLICATING;
2426 addOutputTrack(mainThread);
2427}
2428
2429AudioFlinger::DuplicatingThread::~DuplicatingThread()
2430{
2431 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2432 mOutputTracks[i]->destroy();
2433 }
2434 mOutputTracks.clear();
2435}
2436
2437bool AudioFlinger::DuplicatingThread::threadLoop()
2438{
2439 Vector< sp<Track> > tracksToRemove;
2440 uint32_t mixerStatus = MIXER_IDLE;
2441 nsecs_t standbyTime = systemTime();
2442 size_t mixBufferSize = mFrameCount*mFrameSize;
2443 SortedVector< sp<OutputTrack> > outputTracks;
2444 uint32_t writeFrames = 0;
2445 uint32_t activeSleepTime = activeSleepTimeUs();
2446 uint32_t idleSleepTime = idleSleepTimeUs();
2447 uint32_t sleepTime = idleSleepTime;
2448 Vector< sp<EffectChain> > effectChains;
2449
2450 while (!exitPending())
2451 {
2452 processConfigEvents();
2453
2454 mixerStatus = MIXER_IDLE;
2455 { // scope for the mLock
2456
2457 Mutex::Autolock _l(mLock);
2458
2459 if (checkForNewParameters_l()) {
2460 mixBufferSize = mFrameCount*mFrameSize;
2461 updateWaitTime();
2462 activeSleepTime = activeSleepTimeUs();
2463 idleSleepTime = idleSleepTimeUs();
2464 }
2465
2466 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2467
2468 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2469 outputTracks.add(mOutputTracks[i]);
2470 }
2471
2472 // put audio hardware into standby after short delay
2473 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2474 mSuspended) {
2475 if (!mStandby) {
2476 for (size_t i = 0; i < outputTracks.size(); i++) {
2477 outputTracks[i]->stop();
2478 }
2479 mStandby = true;
2480 mBytesWritten = 0;
2481 }
2482
2483 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2484 // we're about to wait, flush the binder command buffer
2485 IPCThreadState::self()->flushCommands();
2486 outputTracks.clear();
2487
2488 if (exitPending()) break;
2489
2490 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2491 mWaitWorkCV.wait(mLock);
2492 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2493 if (mMasterMute == false) {
2494 char value[PROPERTY_VALUE_MAX];
2495 property_get("ro.audio.silent", value, "0");
2496 if (atoi(value)) {
2497 LOGD("Silence is golden");
2498 setMasterMute(true);
2499 }
2500 }
2501
2502 standbyTime = systemTime() + kStandbyTimeInNsecs;
2503 sleepTime = idleSleepTime;
2504 continue;
2505 }
2506 }
2507
2508 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2509
2510 // prevent any changes in effect chain list and in each effect chain
2511 // during mixing and effect process as the audio buffers could be deleted
2512 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002513 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002514 }
2515
2516 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2517 // mix buffers...
2518 if (outputsReady(outputTracks)) {
2519 mAudioMixer->process();
2520 } else {
2521 memset(mMixBuffer, 0, mixBufferSize);
2522 }
2523 sleepTime = 0;
2524 writeFrames = mFrameCount;
2525 } else {
2526 if (sleepTime == 0) {
2527 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2528 sleepTime = activeSleepTime;
2529 } else {
2530 sleepTime = idleSleepTime;
2531 }
2532 } else if (mBytesWritten != 0) {
2533 // flush remaining overflow buffers in output tracks
2534 for (size_t i = 0; i < outputTracks.size(); i++) {
2535 if (outputTracks[i]->isActive()) {
2536 sleepTime = 0;
2537 writeFrames = 0;
2538 memset(mMixBuffer, 0, mixBufferSize);
2539 break;
2540 }
2541 }
2542 }
2543 }
2544
2545 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002546 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002547 }
2548 // sleepTime == 0 means we must write to audio hardware
2549 if (sleepTime == 0) {
2550 for (size_t i = 0; i < effectChains.size(); i ++) {
2551 effectChains[i]->process_l();
2552 }
2553 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002554 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555
2556 standbyTime = systemTime() + kStandbyTimeInNsecs;
2557 for (size_t i = 0; i < outputTracks.size(); i++) {
2558 outputTracks[i]->write(mMixBuffer, writeFrames);
2559 }
2560 mStandby = false;
2561 mBytesWritten += mixBufferSize;
2562 } else {
2563 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002564 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002565 usleep(sleepTime);
2566 }
2567
2568 // finally let go of all our tracks, without the lock held
2569 // since we can't guarantee the destructors won't acquire that
2570 // same lock.
2571 tracksToRemove.clear();
2572 outputTracks.clear();
2573
2574 // Effect chains will be actually deleted here if they were removed from
2575 // mEffectChains list during mixing or effects processing
2576 effectChains.clear();
2577 }
2578
2579 return false;
2580}
2581
2582void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2583{
2584 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2585 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
2586 this,
2587 mSampleRate,
2588 mFormat,
2589 mChannelCount,
2590 frameCount);
2591 if (outputTrack->cblk() != NULL) {
2592 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
2593 mOutputTracks.add(outputTrack);
2594 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
2595 updateWaitTime();
2596 }
2597}
2598
2599void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2600{
2601 Mutex::Autolock _l(mLock);
2602 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2603 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
2604 mOutputTracks[i]->destroy();
2605 mOutputTracks.removeAt(i);
2606 updateWaitTime();
2607 return;
2608 }
2609 }
2610 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2611}
2612
2613void AudioFlinger::DuplicatingThread::updateWaitTime()
2614{
2615 mWaitTimeMs = UINT_MAX;
2616 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2617 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2618 if (strong != NULL) {
2619 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2620 if (waitTimeMs < mWaitTimeMs) {
2621 mWaitTimeMs = waitTimeMs;
2622 }
2623 }
2624 }
2625}
2626
2627
2628bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2629{
2630 for (size_t i = 0; i < outputTracks.size(); i++) {
2631 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2632 if (thread == 0) {
2633 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2634 return false;
2635 }
2636 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2637 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2638 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2639 return false;
2640 }
2641 }
2642 return true;
2643}
2644
2645uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2646{
2647 return (mWaitTimeMs * 1000) / 2;
2648}
2649
2650// ----------------------------------------------------------------------------
2651
2652// TrackBase constructor must be called with AudioFlinger::mLock held
2653AudioFlinger::ThreadBase::TrackBase::TrackBase(
2654 const wp<ThreadBase>& thread,
2655 const sp<Client>& client,
2656 uint32_t sampleRate,
2657 int format,
2658 int channelCount,
2659 int frameCount,
2660 uint32_t flags,
2661 const sp<IMemory>& sharedBuffer,
2662 int sessionId)
2663 : RefBase(),
2664 mThread(thread),
2665 mClient(client),
2666 mCblk(0),
2667 mFrameCount(0),
2668 mState(IDLE),
2669 mClientTid(-1),
2670 mFormat(format),
2671 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2672 mSessionId(sessionId)
2673{
2674 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2675
2676 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
2677 size_t size = sizeof(audio_track_cblk_t);
2678 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2679 if (sharedBuffer == 0) {
2680 size += bufferSize;
2681 }
2682
2683 if (client != NULL) {
2684 mCblkMemory = client->heap()->allocate(size);
2685 if (mCblkMemory != 0) {
2686 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2687 if (mCblk) { // construct the shared structure in-place.
2688 new(mCblk) audio_track_cblk_t();
2689 // clear all buffers
2690 mCblk->frameCount = frameCount;
2691 mCblk->sampleRate = sampleRate;
2692 mCblk->channelCount = (uint8_t)channelCount;
2693 if (sharedBuffer == 0) {
2694 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2695 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2696 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07002697 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698 mCblk->flags = CBLK_UNDERRUN_ON;
2699 } else {
2700 mBuffer = sharedBuffer->pointer();
2701 }
2702 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2703 }
2704 } else {
2705 LOGE("not enough memory for AudioTrack size=%u", size);
2706 client->heap()->dump("AudioTrack");
2707 return;
2708 }
2709 } else {
2710 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2711 if (mCblk) { // construct the shared structure in-place.
2712 new(mCblk) audio_track_cblk_t();
2713 // clear all buffers
2714 mCblk->frameCount = frameCount;
2715 mCblk->sampleRate = sampleRate;
2716 mCblk->channelCount = (uint8_t)channelCount;
2717 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2718 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2719 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07002720 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002721 mCblk->flags = CBLK_UNDERRUN_ON;
2722 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2723 }
2724 }
2725}
2726
2727AudioFlinger::ThreadBase::TrackBase::~TrackBase()
2728{
2729 if (mCblk) {
2730 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2731 if (mClient == NULL) {
2732 delete mCblk;
2733 }
2734 }
2735 mCblkMemory.clear(); // and free the shared memory
2736 if (mClient != NULL) {
2737 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2738 mClient.clear();
2739 }
2740}
2741
2742void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2743{
2744 buffer->raw = 0;
2745 mFrameCount = buffer->frameCount;
2746 step();
2747 buffer->frameCount = 0;
2748}
2749
2750bool AudioFlinger::ThreadBase::TrackBase::step() {
2751 bool result;
2752 audio_track_cblk_t* cblk = this->cblk();
2753
2754 result = cblk->stepServer(mFrameCount);
2755 if (!result) {
2756 LOGV("stepServer failed acquiring cblk mutex");
2757 mFlags |= STEPSERVER_FAILED;
2758 }
2759 return result;
2760}
2761
2762void AudioFlinger::ThreadBase::TrackBase::reset() {
2763 audio_track_cblk_t* cblk = this->cblk();
2764
2765 cblk->user = 0;
2766 cblk->server = 0;
2767 cblk->userBase = 0;
2768 cblk->serverBase = 0;
2769 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
2770 LOGV("TrackBase::reset");
2771}
2772
2773sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
2774{
2775 return mCblkMemory;
2776}
2777
2778int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
2779 return (int)mCblk->sampleRate;
2780}
2781
2782int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
2783 return (int)mCblk->channelCount;
2784}
2785
2786void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
2787 audio_track_cblk_t* cblk = this->cblk();
2788 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2789 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
2790
2791 // Check validity of returned pointer in case the track control block would have been corrupted.
2792 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2793 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
2794 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
2795 server %d, serverBase %d, user %d, userBase %d, channelCount %d",
2796 bufferStart, bufferEnd, mBuffer, mBufferEnd,
2797 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channelCount);
2798 return 0;
2799 }
2800
2801 return bufferStart;
2802}
2803
2804// ----------------------------------------------------------------------------
2805
2806// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2807AudioFlinger::PlaybackThread::Track::Track(
2808 const wp<ThreadBase>& thread,
2809 const sp<Client>& client,
2810 int streamType,
2811 uint32_t sampleRate,
2812 int format,
2813 int channelCount,
2814 int frameCount,
2815 const sp<IMemory>& sharedBuffer,
2816 int sessionId)
2817 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07002818 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
2819 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002820{
2821 if (mCblk != NULL) {
2822 sp<ThreadBase> baseThread = thread.promote();
2823 if (baseThread != 0) {
2824 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2825 mName = playbackThread->getTrackName_l();
2826 mMainBuffer = playbackThread->mixBuffer();
2827 }
2828 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2829 if (mName < 0) {
2830 LOGE("no more track names available");
2831 }
2832 mVolume[0] = 1.0f;
2833 mVolume[1] = 1.0f;
2834 mStreamType = streamType;
2835 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2836 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2837 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
2838 }
2839}
2840
2841AudioFlinger::PlaybackThread::Track::~Track()
2842{
2843 LOGV("PlaybackThread::Track destructor");
2844 sp<ThreadBase> thread = mThread.promote();
2845 if (thread != 0) {
2846 Mutex::Autolock _l(thread->mLock);
2847 mState = TERMINATED;
2848 }
2849}
2850
2851void AudioFlinger::PlaybackThread::Track::destroy()
2852{
2853 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2854 // by removing it from mTracks vector, so there is a risk that this Tracks's
2855 // desctructor is called. As the destructor needs to lock mLock,
2856 // we must acquire a strong reference on this Track before locking mLock
2857 // here so that the destructor is called only when exiting this function.
2858 // On the other hand, as long as Track::destroy() is only called by
2859 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2860 // this Track with its member mTrack.
2861 sp<Track> keep(this);
2862 { // scope for mLock
2863 sp<ThreadBase> thread = mThread.promote();
2864 if (thread != 0) {
2865 if (!isOutputTrack()) {
2866 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07002867 AudioSystem::stopOutput(thread->id(),
2868 (AudioSystem::stream_type)mStreamType,
2869 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002870
2871 // to track the speaker usage
2872 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873 }
2874 AudioSystem::releaseOutput(thread->id());
2875 }
2876 Mutex::Autolock _l(thread->mLock);
2877 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2878 playbackThread->destroyTrack_l(this);
2879 }
2880 }
2881}
2882
2883void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
2884{
2885 snprintf(buffer, size, " %05d %05d %03u %03u %03u %05u %04u %1d %1d %1d %05u %05u %05u 0x%08x 0x%08x 0x%08x 0x%08x\n",
2886 mName - AudioMixer::TRACK0,
2887 (mClient == NULL) ? getpid() : mClient->pid(),
2888 mStreamType,
2889 mFormat,
2890 mCblk->channelCount,
2891 mSessionId,
2892 mFrameCount,
2893 mState,
2894 mMute,
2895 mFillingUpStatus,
2896 mCblk->sampleRate,
2897 mCblk->volume[0],
2898 mCblk->volume[1],
2899 mCblk->server,
2900 mCblk->user,
2901 (int)mMainBuffer,
2902 (int)mAuxBuffer);
2903}
2904
2905status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
2906{
2907 audio_track_cblk_t* cblk = this->cblk();
2908 uint32_t framesReady;
2909 uint32_t framesReq = buffer->frameCount;
2910
2911 // Check if last stepServer failed, try to step now
2912 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2913 if (!step()) goto getNextBuffer_exit;
2914 LOGV("stepServer recovered");
2915 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2916 }
2917
2918 framesReady = cblk->framesReady();
2919
2920 if (LIKELY(framesReady)) {
2921 uint32_t s = cblk->server;
2922 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2923
2924 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2925 if (framesReq > framesReady) {
2926 framesReq = framesReady;
2927 }
2928 if (s + framesReq > bufferEnd) {
2929 framesReq = bufferEnd - s;
2930 }
2931
2932 buffer->raw = getBuffer(s, framesReq);
2933 if (buffer->raw == 0) goto getNextBuffer_exit;
2934
2935 buffer->frameCount = framesReq;
2936 return NO_ERROR;
2937 }
2938
2939getNextBuffer_exit:
2940 buffer->raw = 0;
2941 buffer->frameCount = 0;
2942 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
2943 return NOT_ENOUGH_DATA;
2944}
2945
2946bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07002947 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002948
2949 if (mCblk->framesReady() >= mCblk->frameCount ||
2950 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
2951 mFillingUpStatus = FS_FILLED;
2952 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
2953 return true;
2954 }
2955 return false;
2956}
2957
2958status_t AudioFlinger::PlaybackThread::Track::start()
2959{
2960 status_t status = NO_ERROR;
Eric Laurentf997cab2010-07-19 06:24:46 -07002961 LOGV("start(%d), calling thread %d session %d",
2962 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002963 sp<ThreadBase> thread = mThread.promote();
2964 if (thread != 0) {
2965 Mutex::Autolock _l(thread->mLock);
2966 int state = mState;
2967 // here the track could be either new, or restarted
2968 // in both cases "unstop" the track
2969 if (mState == PAUSED) {
2970 mState = TrackBase::RESUMING;
2971 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
2972 } else {
2973 mState = TrackBase::ACTIVE;
2974 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
2975 }
2976
2977 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
2978 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07002979 status = AudioSystem::startOutput(thread->id(),
2980 (AudioSystem::stream_type)mStreamType,
2981 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002982 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08002983
2984 // to track the speaker usage
2985 if (status == NO_ERROR) {
2986 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2987 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002988 }
2989 if (status == NO_ERROR) {
2990 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2991 playbackThread->addTrack_l(this);
2992 } else {
2993 mState = state;
2994 }
2995 } else {
2996 status = BAD_VALUE;
2997 }
2998 return status;
2999}
3000
3001void AudioFlinger::PlaybackThread::Track::stop()
3002{
3003 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3004 sp<ThreadBase> thread = mThread.promote();
3005 if (thread != 0) {
3006 Mutex::Autolock _l(thread->mLock);
3007 int state = mState;
3008 if (mState > STOPPED) {
3009 mState = STOPPED;
3010 // If the track is not active (PAUSED and buffers full), flush buffers
3011 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3012 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3013 reset();
3014 }
3015 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3016 }
3017 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3018 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003019 AudioSystem::stopOutput(thread->id(),
3020 (AudioSystem::stream_type)mStreamType,
3021 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003022 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003023
3024 // to track the speaker usage
3025 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026 }
3027 }
3028}
3029
3030void AudioFlinger::PlaybackThread::Track::pause()
3031{
3032 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3033 sp<ThreadBase> thread = mThread.promote();
3034 if (thread != 0) {
3035 Mutex::Autolock _l(thread->mLock);
3036 if (mState == ACTIVE || mState == RESUMING) {
3037 mState = PAUSING;
3038 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3039 if (!isOutputTrack()) {
3040 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003041 AudioSystem::stopOutput(thread->id(),
3042 (AudioSystem::stream_type)mStreamType,
3043 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003045
3046 // to track the speaker usage
3047 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003048 }
3049 }
3050 }
3051}
3052
3053void AudioFlinger::PlaybackThread::Track::flush()
3054{
3055 LOGV("flush(%d)", mName);
3056 sp<ThreadBase> thread = mThread.promote();
3057 if (thread != 0) {
3058 Mutex::Autolock _l(thread->mLock);
3059 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3060 return;
3061 }
3062 // No point remaining in PAUSED state after a flush => go to
3063 // STOPPED state
3064 mState = STOPPED;
3065
3066 mCblk->lock.lock();
3067 // NOTE: reset() will reset cblk->user and cblk->server with
3068 // the risk that at the same time, the AudioMixer is trying to read
3069 // data. In this case, getNextBuffer() would return a NULL pointer
3070 // as audio buffer => the AudioMixer code MUST always test that pointer
3071 // returned by getNextBuffer() is not NULL!
3072 reset();
3073 mCblk->lock.unlock();
3074 }
3075}
3076
3077void AudioFlinger::PlaybackThread::Track::reset()
3078{
3079 // Do not reset twice to avoid discarding data written just after a flush and before
3080 // the audioflinger thread detects the track is stopped.
3081 if (!mResetDone) {
3082 TrackBase::reset();
3083 // Force underrun condition to avoid false underrun callback until first data is
3084 // written to buffer
3085 mCblk->flags |= CBLK_UNDERRUN_ON;
3086 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
3087 mFillingUpStatus = FS_FILLING;
3088 mResetDone = true;
3089 }
3090}
3091
3092void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3093{
3094 mMute = muted;
3095}
3096
3097void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3098{
3099 mVolume[0] = left;
3100 mVolume[1] = right;
3101}
3102
3103status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3104{
3105 status_t status = DEAD_OBJECT;
3106 sp<ThreadBase> thread = mThread.promote();
3107 if (thread != 0) {
3108 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3109 status = playbackThread->attachAuxEffect(this, EffectId);
3110 }
3111 return status;
3112}
3113
3114void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3115{
3116 mAuxEffectId = EffectId;
3117 mAuxBuffer = buffer;
3118}
3119
3120// ----------------------------------------------------------------------------
3121
3122// RecordTrack constructor must be called with AudioFlinger::mLock held
3123AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3124 const wp<ThreadBase>& thread,
3125 const sp<Client>& client,
3126 uint32_t sampleRate,
3127 int format,
3128 int channelCount,
3129 int frameCount,
3130 uint32_t flags,
3131 int sessionId)
3132 : TrackBase(thread, client, sampleRate, format,
3133 channelCount, frameCount, flags, 0, sessionId),
3134 mOverflow(false)
3135{
3136 if (mCblk != NULL) {
3137 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
3138 if (format == AudioSystem::PCM_16_BIT) {
3139 mCblk->frameSize = channelCount * sizeof(int16_t);
3140 } else if (format == AudioSystem::PCM_8_BIT) {
3141 mCblk->frameSize = channelCount * sizeof(int8_t);
3142 } else {
3143 mCblk->frameSize = sizeof(int8_t);
3144 }
3145 }
3146}
3147
3148AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3149{
3150 sp<ThreadBase> thread = mThread.promote();
3151 if (thread != 0) {
3152 AudioSystem::releaseInput(thread->id());
3153 }
3154}
3155
3156status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3157{
3158 audio_track_cblk_t* cblk = this->cblk();
3159 uint32_t framesAvail;
3160 uint32_t framesReq = buffer->frameCount;
3161
3162 // Check if last stepServer failed, try to step now
3163 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3164 if (!step()) goto getNextBuffer_exit;
3165 LOGV("stepServer recovered");
3166 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3167 }
3168
3169 framesAvail = cblk->framesAvailable_l();
3170
3171 if (LIKELY(framesAvail)) {
3172 uint32_t s = cblk->server;
3173 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3174
3175 if (framesReq > framesAvail) {
3176 framesReq = framesAvail;
3177 }
3178 if (s + framesReq > bufferEnd) {
3179 framesReq = bufferEnd - s;
3180 }
3181
3182 buffer->raw = getBuffer(s, framesReq);
3183 if (buffer->raw == 0) goto getNextBuffer_exit;
3184
3185 buffer->frameCount = framesReq;
3186 return NO_ERROR;
3187 }
3188
3189getNextBuffer_exit:
3190 buffer->raw = 0;
3191 buffer->frameCount = 0;
3192 return NOT_ENOUGH_DATA;
3193}
3194
3195status_t AudioFlinger::RecordThread::RecordTrack::start()
3196{
3197 sp<ThreadBase> thread = mThread.promote();
3198 if (thread != 0) {
3199 RecordThread *recordThread = (RecordThread *)thread.get();
3200 return recordThread->start(this);
3201 } else {
3202 return BAD_VALUE;
3203 }
3204}
3205
3206void AudioFlinger::RecordThread::RecordTrack::stop()
3207{
3208 sp<ThreadBase> thread = mThread.promote();
3209 if (thread != 0) {
3210 RecordThread *recordThread = (RecordThread *)thread.get();
3211 recordThread->stop(this);
3212 TrackBase::reset();
3213 // Force overerrun condition to avoid false overrun callback until first data is
3214 // read from buffer
3215 mCblk->flags |= CBLK_UNDERRUN_ON;
3216 }
3217}
3218
3219void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3220{
3221 snprintf(buffer, size, " %05d %03u %03u %05d %04u %01d %05u %08x %08x\n",
3222 (mClient == NULL) ? getpid() : mClient->pid(),
3223 mFormat,
3224 mCblk->channelCount,
3225 mSessionId,
3226 mFrameCount,
3227 mState,
3228 mCblk->sampleRate,
3229 mCblk->server,
3230 mCblk->user);
3231}
3232
3233
3234// ----------------------------------------------------------------------------
3235
3236AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3237 const wp<ThreadBase>& thread,
3238 DuplicatingThread *sourceThread,
3239 uint32_t sampleRate,
3240 int format,
3241 int channelCount,
3242 int frameCount)
3243 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL, 0),
3244 mActive(false), mSourceThread(sourceThread)
3245{
3246
3247 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3248 if (mCblk != NULL) {
3249 mCblk->flags |= CBLK_DIRECTION_OUT;
3250 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3251 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3252 mOutBuffer.frameCount = 0;
3253 playbackThread->mTracks.add(this);
3254 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channelCount %d mBufferEnd %p",
3255 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channelCount, mBufferEnd);
3256 } else {
3257 LOGW("Error creating output track on thread %p", playbackThread);
3258 }
3259}
3260
3261AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3262{
3263 clearBufferQueue();
3264}
3265
3266status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3267{
3268 status_t status = Track::start();
3269 if (status != NO_ERROR) {
3270 return status;
3271 }
3272
3273 mActive = true;
3274 mRetryCount = 127;
3275 return status;
3276}
3277
3278void AudioFlinger::PlaybackThread::OutputTrack::stop()
3279{
3280 Track::stop();
3281 clearBufferQueue();
3282 mOutBuffer.frameCount = 0;
3283 mActive = false;
3284}
3285
3286bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3287{
3288 Buffer *pInBuffer;
3289 Buffer inBuffer;
3290 uint32_t channelCount = mCblk->channelCount;
3291 bool outputBufferFull = false;
3292 inBuffer.frameCount = frames;
3293 inBuffer.i16 = data;
3294
3295 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3296
3297 if (!mActive && frames != 0) {
3298 start();
3299 sp<ThreadBase> thread = mThread.promote();
3300 if (thread != 0) {
3301 MixerThread *mixerThread = (MixerThread *)thread.get();
3302 if (mCblk->frameCount > frames){
3303 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3304 uint32_t startFrames = (mCblk->frameCount - frames);
3305 pInBuffer = new Buffer;
3306 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3307 pInBuffer->frameCount = startFrames;
3308 pInBuffer->i16 = pInBuffer->mBuffer;
3309 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3310 mBufferQueue.add(pInBuffer);
3311 } else {
3312 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3313 }
3314 }
3315 }
3316 }
3317
3318 while (waitTimeLeftMs) {
3319 // First write pending buffers, then new data
3320 if (mBufferQueue.size()) {
3321 pInBuffer = mBufferQueue.itemAt(0);
3322 } else {
3323 pInBuffer = &inBuffer;
3324 }
3325
3326 if (pInBuffer->frameCount == 0) {
3327 break;
3328 }
3329
3330 if (mOutBuffer.frameCount == 0) {
3331 mOutBuffer.frameCount = pInBuffer->frameCount;
3332 nsecs_t startTime = systemTime();
3333 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
3334 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
3335 outputBufferFull = true;
3336 break;
3337 }
3338 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3339 if (waitTimeLeftMs >= waitTimeMs) {
3340 waitTimeLeftMs -= waitTimeMs;
3341 } else {
3342 waitTimeLeftMs = 0;
3343 }
3344 }
3345
3346 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3347 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3348 mCblk->stepUser(outFrames);
3349 pInBuffer->frameCount -= outFrames;
3350 pInBuffer->i16 += outFrames * channelCount;
3351 mOutBuffer.frameCount -= outFrames;
3352 mOutBuffer.i16 += outFrames * channelCount;
3353
3354 if (pInBuffer->frameCount == 0) {
3355 if (mBufferQueue.size()) {
3356 mBufferQueue.removeAt(0);
3357 delete [] pInBuffer->mBuffer;
3358 delete pInBuffer;
3359 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3360 } else {
3361 break;
3362 }
3363 }
3364 }
3365
3366 // If we could not write all frames, allocate a buffer and queue it for next time.
3367 if (inBuffer.frameCount) {
3368 sp<ThreadBase> thread = mThread.promote();
3369 if (thread != 0 && !thread->standby()) {
3370 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3371 pInBuffer = new Buffer;
3372 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3373 pInBuffer->frameCount = inBuffer.frameCount;
3374 pInBuffer->i16 = pInBuffer->mBuffer;
3375 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3376 mBufferQueue.add(pInBuffer);
3377 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3378 } else {
3379 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3380 }
3381 }
3382 }
3383
3384 // Calling write() with a 0 length buffer, means that no more data will be written:
3385 // If no more buffers are pending, fill output track buffer to make sure it is started
3386 // by output mixer.
3387 if (frames == 0 && mBufferQueue.size() == 0) {
3388 if (mCblk->user < mCblk->frameCount) {
3389 frames = mCblk->frameCount - mCblk->user;
3390 pInBuffer = new Buffer;
3391 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3392 pInBuffer->frameCount = frames;
3393 pInBuffer->i16 = pInBuffer->mBuffer;
3394 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3395 mBufferQueue.add(pInBuffer);
3396 } else if (mActive) {
3397 stop();
3398 }
3399 }
3400
3401 return outputBufferFull;
3402}
3403
3404status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3405{
3406 int active;
3407 status_t result;
3408 audio_track_cblk_t* cblk = mCblk;
3409 uint32_t framesReq = buffer->frameCount;
3410
3411// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
3412 buffer->frameCount = 0;
3413
3414 uint32_t framesAvail = cblk->framesAvailable();
3415
3416
3417 if (framesAvail == 0) {
3418 Mutex::Autolock _l(cblk->lock);
3419 goto start_loop_here;
3420 while (framesAvail == 0) {
3421 active = mActive;
3422 if (UNLIKELY(!active)) {
3423 LOGV("Not active and NO_MORE_BUFFERS");
3424 return AudioTrack::NO_MORE_BUFFERS;
3425 }
3426 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3427 if (result != NO_ERROR) {
3428 return AudioTrack::NO_MORE_BUFFERS;
3429 }
3430 // read the server count again
3431 start_loop_here:
3432 framesAvail = cblk->framesAvailable_l();
3433 }
3434 }
3435
3436// if (framesAvail < framesReq) {
3437// return AudioTrack::NO_MORE_BUFFERS;
3438// }
3439
3440 if (framesReq > framesAvail) {
3441 framesReq = framesAvail;
3442 }
3443
3444 uint32_t u = cblk->user;
3445 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3446
3447 if (u + framesReq > bufferEnd) {
3448 framesReq = bufferEnd - u;
3449 }
3450
3451 buffer->frameCount = framesReq;
3452 buffer->raw = (void *)cblk->buffer(u);
3453 return NO_ERROR;
3454}
3455
3456
3457void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3458{
3459 size_t size = mBufferQueue.size();
3460 Buffer *pBuffer;
3461
3462 for (size_t i = 0; i < size; i++) {
3463 pBuffer = mBufferQueue.itemAt(i);
3464 delete [] pBuffer->mBuffer;
3465 delete pBuffer;
3466 }
3467 mBufferQueue.clear();
3468}
3469
3470// ----------------------------------------------------------------------------
3471
3472AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3473 : RefBase(),
3474 mAudioFlinger(audioFlinger),
3475 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
3476 mPid(pid)
3477{
3478 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3479}
3480
3481// Client destructor must be called with AudioFlinger::mLock held
3482AudioFlinger::Client::~Client()
3483{
3484 mAudioFlinger->removeClient_l(mPid);
3485}
3486
3487const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3488{
3489 return mMemoryDealer;
3490}
3491
3492// ----------------------------------------------------------------------------
3493
3494AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3495 const sp<IAudioFlingerClient>& client,
3496 pid_t pid)
3497 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3498{
3499}
3500
3501AudioFlinger::NotificationClient::~NotificationClient()
3502{
3503 mClient.clear();
3504}
3505
3506void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3507{
3508 sp<NotificationClient> keep(this);
3509 {
3510 mAudioFlinger->removeNotificationClient(mPid);
3511 }
3512}
3513
3514// ----------------------------------------------------------------------------
3515
3516AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
3517 : BnAudioTrack(),
3518 mTrack(track)
3519{
3520}
3521
3522AudioFlinger::TrackHandle::~TrackHandle() {
3523 // just stop the track on deletion, associated resources
3524 // will be freed from the main thread once all pending buffers have
3525 // been played. Unless it's not in the active track list, in which
3526 // case we free everything now...
3527 mTrack->destroy();
3528}
3529
3530status_t AudioFlinger::TrackHandle::start() {
3531 return mTrack->start();
3532}
3533
3534void AudioFlinger::TrackHandle::stop() {
3535 mTrack->stop();
3536}
3537
3538void AudioFlinger::TrackHandle::flush() {
3539 mTrack->flush();
3540}
3541
3542void AudioFlinger::TrackHandle::mute(bool e) {
3543 mTrack->mute(e);
3544}
3545
3546void AudioFlinger::TrackHandle::pause() {
3547 mTrack->pause();
3548}
3549
3550void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3551 mTrack->setVolume(left, right);
3552}
3553
3554sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3555 return mTrack->getCblk();
3556}
3557
3558status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3559{
3560 return mTrack->attachAuxEffect(EffectId);
3561}
3562
3563status_t AudioFlinger::TrackHandle::onTransact(
3564 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3565{
3566 return BnAudioTrack::onTransact(code, data, reply, flags);
3567}
3568
3569// ----------------------------------------------------------------------------
3570
3571sp<IAudioRecord> AudioFlinger::openRecord(
3572 pid_t pid,
3573 int input,
3574 uint32_t sampleRate,
3575 int format,
3576 int channelCount,
3577 int frameCount,
3578 uint32_t flags,
3579 int *sessionId,
3580 status_t *status)
3581{
3582 sp<RecordThread::RecordTrack> recordTrack;
3583 sp<RecordHandle> recordHandle;
3584 sp<Client> client;
3585 wp<Client> wclient;
3586 status_t lStatus;
3587 RecordThread *thread;
3588 size_t inFrameCount;
3589 int lSessionId;
3590
3591 // check calling permissions
3592 if (!recordingAllowed()) {
3593 lStatus = PERMISSION_DENIED;
3594 goto Exit;
3595 }
3596
3597 // add client to list
3598 { // scope for mLock
3599 Mutex::Autolock _l(mLock);
3600 thread = checkRecordThread_l(input);
3601 if (thread == NULL) {
3602 lStatus = BAD_VALUE;
3603 goto Exit;
3604 }
3605
3606 wclient = mClients.valueFor(pid);
3607 if (wclient != NULL) {
3608 client = wclient.promote();
3609 } else {
3610 client = new Client(this, pid);
3611 mClients.add(pid, client);
3612 }
3613
3614 // If no audio session id is provided, create one here
Eric Laurentde070132010-07-13 04:45:46 -07003615 if (sessionId != NULL && *sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003616 lSessionId = *sessionId;
3617 } else {
Eric Laurentf5aafb22010-11-18 08:40:16 -08003618 lSessionId = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003619 if (sessionId != NULL) {
3620 *sessionId = lSessionId;
3621 }
3622 }
3623 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
3624 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
3625 format, channelCount, frameCount, flags, lSessionId);
3626 }
3627 if (recordTrack->getCblk() == NULL) {
3628 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3629 // destructor is called by the TrackBase destructor with mLock held
3630 client.clear();
3631 recordTrack.clear();
3632 lStatus = NO_MEMORY;
3633 goto Exit;
3634 }
3635
3636 // return to handle to client
3637 recordHandle = new RecordHandle(recordTrack);
3638 lStatus = NO_ERROR;
3639
3640Exit:
3641 if (status) {
3642 *status = lStatus;
3643 }
3644 return recordHandle;
3645}
3646
3647// ----------------------------------------------------------------------------
3648
3649AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
3650 : BnAudioRecord(),
3651 mRecordTrack(recordTrack)
3652{
3653}
3654
3655AudioFlinger::RecordHandle::~RecordHandle() {
3656 stop();
3657}
3658
3659status_t AudioFlinger::RecordHandle::start() {
3660 LOGV("RecordHandle::start()");
3661 return mRecordTrack->start();
3662}
3663
3664void AudioFlinger::RecordHandle::stop() {
3665 LOGV("RecordHandle::stop()");
3666 mRecordTrack->stop();
3667}
3668
3669sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3670 return mRecordTrack->getCblk();
3671}
3672
3673status_t AudioFlinger::RecordHandle::onTransact(
3674 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3675{
3676 return BnAudioRecord::onTransact(code, data, reply, flags);
3677}
3678
3679// ----------------------------------------------------------------------------
3680
3681AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
3682 ThreadBase(audioFlinger, id),
3683 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
3684{
3685 mReqChannelCount = AudioSystem::popCount(channels);
3686 mReqSampleRate = sampleRate;
3687 readInputParameters();
3688}
3689
3690
3691AudioFlinger::RecordThread::~RecordThread()
3692{
3693 delete[] mRsmpInBuffer;
3694 if (mResampler != 0) {
3695 delete mResampler;
3696 delete[] mRsmpOutBuffer;
3697 }
3698}
3699
3700void AudioFlinger::RecordThread::onFirstRef()
3701{
3702 const size_t SIZE = 256;
3703 char buffer[SIZE];
3704
3705 snprintf(buffer, SIZE, "Record Thread %p", this);
3706
3707 run(buffer, PRIORITY_URGENT_AUDIO);
3708}
3709
3710bool AudioFlinger::RecordThread::threadLoop()
3711{
3712 AudioBufferProvider::Buffer buffer;
3713 sp<RecordTrack> activeTrack;
3714
Eric Laurent44d98482010-09-30 16:12:31 -07003715 nsecs_t lastWarning = 0;
3716
Mathias Agopian65ab4712010-07-14 17:59:35 -07003717 // start recording
3718 while (!exitPending()) {
3719
3720 processConfigEvents();
3721
3722 { // scope for mLock
3723 Mutex::Autolock _l(mLock);
3724 checkForNewParameters_l();
3725 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3726 if (!mStandby) {
3727 mInput->standby();
3728 mStandby = true;
3729 }
3730
3731 if (exitPending()) break;
3732
3733 LOGV("RecordThread: loop stopping");
3734 // go to sleep
3735 mWaitWorkCV.wait(mLock);
3736 LOGV("RecordThread: loop starting");
3737 continue;
3738 }
3739 if (mActiveTrack != 0) {
3740 if (mActiveTrack->mState == TrackBase::PAUSING) {
3741 if (!mStandby) {
3742 mInput->standby();
3743 mStandby = true;
3744 }
3745 mActiveTrack.clear();
3746 mStartStopCond.broadcast();
3747 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
3748 if (mReqChannelCount != mActiveTrack->channelCount()) {
3749 mActiveTrack.clear();
3750 mStartStopCond.broadcast();
3751 } else if (mBytesRead != 0) {
3752 // record start succeeds only if first read from audio input
3753 // succeeds
3754 if (mBytesRead > 0) {
3755 mActiveTrack->mState = TrackBase::ACTIVE;
3756 } else {
3757 mActiveTrack.clear();
3758 }
3759 mStartStopCond.broadcast();
3760 }
3761 mStandby = false;
3762 }
3763 }
3764 }
3765
3766 if (mActiveTrack != 0) {
3767 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3768 mActiveTrack->mState != TrackBase::RESUMING) {
3769 usleep(5000);
3770 continue;
3771 }
3772 buffer.frameCount = mFrameCount;
3773 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3774 size_t framesOut = buffer.frameCount;
3775 if (mResampler == 0) {
3776 // no resampling
3777 while (framesOut) {
3778 size_t framesIn = mFrameCount - mRsmpInIndex;
3779 if (framesIn) {
3780 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3781 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3782 if (framesIn > framesOut)
3783 framesIn = framesOut;
3784 mRsmpInIndex += framesIn;
3785 framesOut -= framesIn;
3786 if ((int)mChannelCount == mReqChannelCount ||
3787 mFormat != AudioSystem::PCM_16_BIT) {
3788 memcpy(dst, src, framesIn * mFrameSize);
3789 } else {
3790 int16_t *src16 = (int16_t *)src;
3791 int16_t *dst16 = (int16_t *)dst;
3792 if (mChannelCount == 1) {
3793 while (framesIn--) {
3794 *dst16++ = *src16;
3795 *dst16++ = *src16++;
3796 }
3797 } else {
3798 while (framesIn--) {
3799 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3800 src16 += 2;
3801 }
3802 }
3803 }
3804 }
3805 if (framesOut && mFrameCount == mRsmpInIndex) {
3806 if (framesOut == mFrameCount &&
3807 ((int)mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
3808 mBytesRead = mInput->read(buffer.raw, mInputBytes);
3809 framesOut = 0;
3810 } else {
3811 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3812 mRsmpInIndex = 0;
3813 }
3814 if (mBytesRead < 0) {
3815 LOGE("Error reading audio input");
3816 if (mActiveTrack->mState == TrackBase::ACTIVE) {
3817 // Force input into standby so that it tries to
3818 // recover at next read attempt
3819 mInput->standby();
3820 usleep(5000);
3821 }
3822 mRsmpInIndex = mFrameCount;
3823 framesOut = 0;
3824 buffer.frameCount = 0;
3825 }
3826 }
3827 }
3828 } else {
3829 // resampling
3830
3831 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3832 // alter output frame count as if we were expecting stereo samples
3833 if (mChannelCount == 1 && mReqChannelCount == 1) {
3834 framesOut >>= 1;
3835 }
3836 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3837 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3838 // are 32 bit aligned which should be always true.
3839 if (mChannelCount == 2 && mReqChannelCount == 1) {
3840 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3841 // the resampler always outputs stereo samples: do post stereo to mono conversion
3842 int16_t *src = (int16_t *)mRsmpOutBuffer;
3843 int16_t *dst = buffer.i16;
3844 while (framesOut--) {
3845 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3846 src += 2;
3847 }
3848 } else {
3849 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3850 }
3851
3852 }
3853 mActiveTrack->releaseBuffer(&buffer);
3854 mActiveTrack->overflow();
3855 }
3856 // client isn't retrieving buffers fast enough
3857 else {
Eric Laurent44d98482010-09-30 16:12:31 -07003858 if (!mActiveTrack->setOverflow()) {
3859 nsecs_t now = systemTime();
3860 if ((now - lastWarning) > kWarningThrottle) {
3861 LOGW("RecordThread: buffer overflow");
3862 lastWarning = now;
3863 }
3864 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003865 // Release the processor for a while before asking for a new buffer.
3866 // This will give the application more chance to read from the buffer and
3867 // clear the overflow.
3868 usleep(5000);
3869 }
3870 }
3871 }
3872
3873 if (!mStandby) {
3874 mInput->standby();
3875 }
3876 mActiveTrack.clear();
3877
3878 mStartStopCond.broadcast();
3879
3880 LOGV("RecordThread %p exiting", this);
3881 return false;
3882}
3883
3884status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
3885{
3886 LOGV("RecordThread::start");
3887 sp <ThreadBase> strongMe = this;
3888 status_t status = NO_ERROR;
3889 {
3890 AutoMutex lock(&mLock);
3891 if (mActiveTrack != 0) {
3892 if (recordTrack != mActiveTrack.get()) {
3893 status = -EBUSY;
3894 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
3895 mActiveTrack->mState = TrackBase::ACTIVE;
3896 }
3897 return status;
3898 }
3899
3900 recordTrack->mState = TrackBase::IDLE;
3901 mActiveTrack = recordTrack;
3902 mLock.unlock();
3903 status_t status = AudioSystem::startInput(mId);
3904 mLock.lock();
3905 if (status != NO_ERROR) {
3906 mActiveTrack.clear();
3907 return status;
3908 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003909 mRsmpInIndex = mFrameCount;
3910 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08003911 if (mResampler != NULL) {
3912 mResampler->reset();
3913 }
3914 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003915 // signal thread to start
3916 LOGV("Signal record thread");
3917 mWaitWorkCV.signal();
3918 // do not wait for mStartStopCond if exiting
3919 if (mExiting) {
3920 mActiveTrack.clear();
3921 status = INVALID_OPERATION;
3922 goto startError;
3923 }
3924 mStartStopCond.wait(mLock);
3925 if (mActiveTrack == 0) {
3926 LOGV("Record failed to start");
3927 status = BAD_VALUE;
3928 goto startError;
3929 }
3930 LOGV("Record started OK");
3931 return status;
3932 }
3933startError:
3934 AudioSystem::stopInput(mId);
3935 return status;
3936}
3937
3938void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3939 LOGV("RecordThread::stop");
3940 sp <ThreadBase> strongMe = this;
3941 {
3942 AutoMutex lock(&mLock);
3943 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3944 mActiveTrack->mState = TrackBase::PAUSING;
3945 // do not wait for mStartStopCond if exiting
3946 if (mExiting) {
3947 return;
3948 }
3949 mStartStopCond.wait(mLock);
3950 // if we have been restarted, recordTrack == mActiveTrack.get() here
3951 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
3952 mLock.unlock();
3953 AudioSystem::stopInput(mId);
3954 mLock.lock();
3955 LOGV("Record stopped OK");
3956 }
3957 }
3958 }
3959}
3960
3961status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
3962{
3963 const size_t SIZE = 256;
3964 char buffer[SIZE];
3965 String8 result;
3966 pid_t pid = 0;
3967
3968 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
3969 result.append(buffer);
3970
3971 if (mActiveTrack != 0) {
3972 result.append("Active Track:\n");
3973 result.append(" Clien Fmt Chn Session Buf S SRate Serv User\n");
3974 mActiveTrack->dump(buffer, SIZE);
3975 result.append(buffer);
3976
3977 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
3978 result.append(buffer);
3979 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
3980 result.append(buffer);
3981 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
3982 result.append(buffer);
3983 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
3984 result.append(buffer);
3985 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
3986 result.append(buffer);
3987
3988
3989 } else {
3990 result.append("No record client\n");
3991 }
3992 write(fd, result.string(), result.size());
3993
3994 dumpBase(fd, args);
3995
3996 return NO_ERROR;
3997}
3998
3999status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4000{
4001 size_t framesReq = buffer->frameCount;
4002 size_t framesReady = mFrameCount - mRsmpInIndex;
4003 int channelCount;
4004
4005 if (framesReady == 0) {
4006 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
4007 if (mBytesRead < 0) {
4008 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4009 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4010 // Force input into standby so that it tries to
4011 // recover at next read attempt
4012 mInput->standby();
4013 usleep(5000);
4014 }
4015 buffer->raw = 0;
4016 buffer->frameCount = 0;
4017 return NOT_ENOUGH_DATA;
4018 }
4019 mRsmpInIndex = 0;
4020 framesReady = mFrameCount;
4021 }
4022
4023 if (framesReq > framesReady) {
4024 framesReq = framesReady;
4025 }
4026
4027 if (mChannelCount == 1 && mReqChannelCount == 2) {
4028 channelCount = 1;
4029 } else {
4030 channelCount = 2;
4031 }
4032 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4033 buffer->frameCount = framesReq;
4034 return NO_ERROR;
4035}
4036
4037void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4038{
4039 mRsmpInIndex += buffer->frameCount;
4040 buffer->frameCount = 0;
4041}
4042
4043bool AudioFlinger::RecordThread::checkForNewParameters_l()
4044{
4045 bool reconfig = false;
4046
4047 while (!mNewParameters.isEmpty()) {
4048 status_t status = NO_ERROR;
4049 String8 keyValuePair = mNewParameters[0];
4050 AudioParameter param = AudioParameter(keyValuePair);
4051 int value;
4052 int reqFormat = mFormat;
4053 int reqSamplingRate = mReqSampleRate;
4054 int reqChannelCount = mReqChannelCount;
4055
4056 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4057 reqSamplingRate = value;
4058 reconfig = true;
4059 }
4060 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4061 reqFormat = value;
4062 reconfig = true;
4063 }
4064 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4065 reqChannelCount = AudioSystem::popCount(value);
4066 reconfig = true;
4067 }
4068 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4069 // do not accept frame count changes if tracks are open as the track buffer
4070 // size depends on frame count and correct behavior would not be garantied
4071 // if frame count is changed after track creation
4072 if (mActiveTrack != 0) {
4073 status = INVALID_OPERATION;
4074 } else {
4075 reconfig = true;
4076 }
4077 }
4078 if (status == NO_ERROR) {
4079 status = mInput->setParameters(keyValuePair);
4080 if (status == INVALID_OPERATION) {
4081 mInput->standby();
4082 status = mInput->setParameters(keyValuePair);
4083 }
4084 if (reconfig) {
4085 if (status == BAD_VALUE &&
4086 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
4087 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
4088 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
4089 status = NO_ERROR;
4090 }
4091 if (status == NO_ERROR) {
4092 readInputParameters();
4093 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4094 }
4095 }
4096 }
4097
4098 mNewParameters.removeAt(0);
4099
4100 mParamStatus = status;
4101 mParamCond.signal();
4102 mWaitWorkCV.wait(mLock);
4103 }
4104 return reconfig;
4105}
4106
4107String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4108{
4109 return mInput->getParameters(keys);
4110}
4111
4112void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4113 AudioSystem::OutputDescriptor desc;
4114 void *param2 = 0;
4115
4116 switch (event) {
4117 case AudioSystem::INPUT_OPENED:
4118 case AudioSystem::INPUT_CONFIG_CHANGED:
4119 desc.channels = mChannels;
4120 desc.samplingRate = mSampleRate;
4121 desc.format = mFormat;
4122 desc.frameCount = mFrameCount;
4123 desc.latency = 0;
4124 param2 = &desc;
4125 break;
4126
4127 case AudioSystem::INPUT_CLOSED:
4128 default:
4129 break;
4130 }
4131 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4132}
4133
4134void AudioFlinger::RecordThread::readInputParameters()
4135{
4136 if (mRsmpInBuffer) delete mRsmpInBuffer;
4137 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4138 if (mResampler) delete mResampler;
4139 mResampler = 0;
4140
4141 mSampleRate = mInput->sampleRate();
4142 mChannels = mInput->channels();
4143 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
4144 mFormat = mInput->format();
4145 mFrameSize = (uint16_t)mInput->frameSize();
4146 mInputBytes = mInput->bufferSize();
4147 mFrameCount = mInputBytes / mFrameSize;
4148 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4149
4150 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4151 {
4152 int channelCount;
4153 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4154 // stereo to mono post process as the resampler always outputs stereo.
4155 if (mChannelCount == 1 && mReqChannelCount == 2) {
4156 channelCount = 1;
4157 } else {
4158 channelCount = 2;
4159 }
4160 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4161 mResampler->setSampleRate(mSampleRate);
4162 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4163 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4164
4165 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4166 if (mChannelCount == 1 && mReqChannelCount == 1) {
4167 mFrameCount >>= 1;
4168 }
4169
4170 }
4171 mRsmpInIndex = mFrameCount;
4172}
4173
4174unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4175{
4176 return mInput->getInputFramesLost();
4177}
4178
4179// ----------------------------------------------------------------------------
4180
4181int AudioFlinger::openOutput(uint32_t *pDevices,
4182 uint32_t *pSamplingRate,
4183 uint32_t *pFormat,
4184 uint32_t *pChannels,
4185 uint32_t *pLatencyMs,
4186 uint32_t flags)
4187{
4188 status_t status;
4189 PlaybackThread *thread = NULL;
4190 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4191 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4192 uint32_t format = pFormat ? *pFormat : 0;
4193 uint32_t channels = pChannels ? *pChannels : 0;
4194 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
4195
4196 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4197 pDevices ? *pDevices : 0,
4198 samplingRate,
4199 format,
4200 channels,
4201 flags);
4202
4203 if (pDevices == NULL || *pDevices == 0) {
4204 return 0;
4205 }
4206 Mutex::Autolock _l(mLock);
4207
4208 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
4209 (int *)&format,
4210 &channels,
4211 &samplingRate,
4212 &status);
4213 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
4214 output,
4215 samplingRate,
4216 format,
4217 channels,
4218 status);
4219
4220 mHardwareStatus = AUDIO_HW_IDLE;
4221 if (output != 0) {
Eric Laurentf5aafb22010-11-18 08:40:16 -08004222 int id = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004223 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
4224 (format != AudioSystem::PCM_16_BIT) ||
4225 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
4226 thread = new DirectOutputThread(this, output, id, *pDevices);
4227 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4228 } else {
4229 thread = new MixerThread(this, output, id, *pDevices);
4230 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004231 }
4232 mPlaybackThreads.add(id, thread);
4233
4234 if (pSamplingRate) *pSamplingRate = samplingRate;
4235 if (pFormat) *pFormat = format;
4236 if (pChannels) *pChannels = channels;
4237 if (pLatencyMs) *pLatencyMs = thread->latency();
4238
4239 // notify client processes of the new output creation
4240 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4241 return id;
4242 }
4243
4244 return 0;
4245}
4246
4247int AudioFlinger::openDuplicateOutput(int output1, int output2)
4248{
4249 Mutex::Autolock _l(mLock);
4250 MixerThread *thread1 = checkMixerThread_l(output1);
4251 MixerThread *thread2 = checkMixerThread_l(output2);
4252
4253 if (thread1 == NULL || thread2 == NULL) {
4254 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4255 return 0;
4256 }
4257
Eric Laurentf5aafb22010-11-18 08:40:16 -08004258 int id = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4260 thread->addOutputTrack(thread2);
4261 mPlaybackThreads.add(id, thread);
4262 // notify client processes of the new output creation
4263 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4264 return id;
4265}
4266
4267status_t AudioFlinger::closeOutput(int output)
4268{
4269 // keep strong reference on the playback thread so that
4270 // it is not destroyed while exit() is executed
4271 sp <PlaybackThread> thread;
4272 {
4273 Mutex::Autolock _l(mLock);
4274 thread = checkPlaybackThread_l(output);
4275 if (thread == NULL) {
4276 return BAD_VALUE;
4277 }
4278
4279 LOGV("closeOutput() %d", output);
4280
4281 if (thread->type() == PlaybackThread::MIXER) {
4282 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4283 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4284 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4285 dupThread->removeOutputTrack((MixerThread *)thread.get());
4286 }
4287 }
4288 }
4289 void *param2 = 0;
4290 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4291 mPlaybackThreads.removeItem(output);
4292 }
4293 thread->exit();
4294
4295 if (thread->type() != PlaybackThread::DUPLICATING) {
4296 mAudioHardware->closeOutputStream(thread->getOutput());
4297 }
4298 return NO_ERROR;
4299}
4300
4301status_t AudioFlinger::suspendOutput(int output)
4302{
4303 Mutex::Autolock _l(mLock);
4304 PlaybackThread *thread = checkPlaybackThread_l(output);
4305
4306 if (thread == NULL) {
4307 return BAD_VALUE;
4308 }
4309
4310 LOGV("suspendOutput() %d", output);
4311 thread->suspend();
4312
4313 return NO_ERROR;
4314}
4315
4316status_t AudioFlinger::restoreOutput(int output)
4317{
4318 Mutex::Autolock _l(mLock);
4319 PlaybackThread *thread = checkPlaybackThread_l(output);
4320
4321 if (thread == NULL) {
4322 return BAD_VALUE;
4323 }
4324
4325 LOGV("restoreOutput() %d", output);
4326
4327 thread->restore();
4328
4329 return NO_ERROR;
4330}
4331
4332int AudioFlinger::openInput(uint32_t *pDevices,
4333 uint32_t *pSamplingRate,
4334 uint32_t *pFormat,
4335 uint32_t *pChannels,
4336 uint32_t acoustics)
4337{
4338 status_t status;
4339 RecordThread *thread = NULL;
4340 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4341 uint32_t format = pFormat ? *pFormat : 0;
4342 uint32_t channels = pChannels ? *pChannels : 0;
4343 uint32_t reqSamplingRate = samplingRate;
4344 uint32_t reqFormat = format;
4345 uint32_t reqChannels = channels;
4346
4347 if (pDevices == NULL || *pDevices == 0) {
4348 return 0;
4349 }
4350 Mutex::Autolock _l(mLock);
4351
4352 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
4353 (int *)&format,
4354 &channels,
4355 &samplingRate,
4356 &status,
4357 (AudioSystem::audio_in_acoustics)acoustics);
4358 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
4359 input,
4360 samplingRate,
4361 format,
4362 channels,
4363 acoustics,
4364 status);
4365
4366 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4367 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4368 // or stereo to mono conversions on 16 bit PCM inputs.
4369 if (input == 0 && status == BAD_VALUE &&
4370 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
4371 (samplingRate <= 2 * reqSamplingRate) &&
4372 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
4373 LOGV("openInput() reopening with proposed sampling rate and channels");
4374 input = mAudioHardware->openInputStream(*pDevices,
4375 (int *)&format,
4376 &channels,
4377 &samplingRate,
4378 &status,
4379 (AudioSystem::audio_in_acoustics)acoustics);
4380 }
4381
4382 if (input != 0) {
Eric Laurentf5aafb22010-11-18 08:40:16 -08004383 int id = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384 // Start record thread
4385 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4386 mRecordThreads.add(id, thread);
4387 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
4388 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4389 if (pFormat) *pFormat = format;
4390 if (pChannels) *pChannels = reqChannels;
4391
4392 input->standby();
4393
4394 // notify client processes of the new input creation
4395 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
4396 return id;
4397 }
4398
4399 return 0;
4400}
4401
4402status_t AudioFlinger::closeInput(int input)
4403{
4404 // keep strong reference on the record thread so that
4405 // it is not destroyed while exit() is executed
4406 sp <RecordThread> thread;
4407 {
4408 Mutex::Autolock _l(mLock);
4409 thread = checkRecordThread_l(input);
4410 if (thread == NULL) {
4411 return BAD_VALUE;
4412 }
4413
4414 LOGV("closeInput() %d", input);
4415 void *param2 = 0;
4416 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
4417 mRecordThreads.removeItem(input);
4418 }
4419 thread->exit();
4420
4421 mAudioHardware->closeInputStream(thread->getInput());
4422
4423 return NO_ERROR;
4424}
4425
4426status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
4427{
4428 Mutex::Autolock _l(mLock);
4429 MixerThread *dstThread = checkMixerThread_l(output);
4430 if (dstThread == NULL) {
4431 LOGW("setStreamOutput() bad output id %d", output);
4432 return BAD_VALUE;
4433 }
4434
4435 LOGV("setStreamOutput() stream %d to output %d", stream, output);
4436 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
4437
4438 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4439 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
4440 if (thread != dstThread &&
4441 thread->type() != PlaybackThread::DIRECT) {
4442 MixerThread *srcThread = (MixerThread *)thread;
4443 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004444 }
Eric Laurentde070132010-07-13 04:45:46 -07004445 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004446
4447 return NO_ERROR;
4448}
4449
4450
4451int AudioFlinger::newAudioSessionId()
4452{
Eric Laurentf5aafb22010-11-18 08:40:16 -08004453 AutoMutex _l(mLock);
4454 return nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004455}
4456
4457// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
4458AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
4459{
4460 PlaybackThread *thread = NULL;
4461 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4462 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
4463 }
4464 return thread;
4465}
4466
4467// checkMixerThread_l() must be called with AudioFlinger::mLock held
4468AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
4469{
4470 PlaybackThread *thread = checkPlaybackThread_l(output);
4471 if (thread != NULL) {
4472 if (thread->type() == PlaybackThread::DIRECT) {
4473 thread = NULL;
4474 }
4475 }
4476 return (MixerThread *)thread;
4477}
4478
4479// checkRecordThread_l() must be called with AudioFlinger::mLock held
4480AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
4481{
4482 RecordThread *thread = NULL;
4483 if (mRecordThreads.indexOfKey(input) >= 0) {
4484 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
4485 }
4486 return thread;
4487}
4488
Eric Laurentf5aafb22010-11-18 08:40:16 -08004489// nextUniqueId_l() must be called with AudioFlinger::mLock held
4490int AudioFlinger::nextUniqueId_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491{
Eric Laurentf5aafb22010-11-18 08:40:16 -08004492 return mNextUniqueId++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004493}
4494
4495// ----------------------------------------------------------------------------
4496// Effect management
4497// ----------------------------------------------------------------------------
4498
4499
4500status_t AudioFlinger::loadEffectLibrary(const char *libPath, int *handle)
4501{
Eric Laurentde070132010-07-13 04:45:46 -07004502 // check calling permissions
4503 if (!settingsAllowed()) {
4504 return PERMISSION_DENIED;
4505 }
4506 // only allow libraries loaded from /system/lib/soundfx for now
4507 if (strncmp(gEffectLibPath, libPath, strlen(gEffectLibPath)) != 0) {
4508 return PERMISSION_DENIED;
4509 }
4510
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511 Mutex::Autolock _l(mLock);
4512 return EffectLoadLibrary(libPath, handle);
4513}
4514
4515status_t AudioFlinger::unloadEffectLibrary(int handle)
4516{
Eric Laurentde070132010-07-13 04:45:46 -07004517 // check calling permissions
4518 if (!settingsAllowed()) {
4519 return PERMISSION_DENIED;
4520 }
4521
Mathias Agopian65ab4712010-07-14 17:59:35 -07004522 Mutex::Autolock _l(mLock);
4523 return EffectUnloadLibrary(handle);
4524}
4525
4526status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4527{
4528 Mutex::Autolock _l(mLock);
4529 return EffectQueryNumberEffects(numEffects);
4530}
4531
4532status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
4533{
4534 Mutex::Autolock _l(mLock);
4535 return EffectQueryEffect(index, descriptor);
4536}
4537
4538status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4539{
4540 Mutex::Autolock _l(mLock);
4541 return EffectGetDescriptor(pUuid, descriptor);
4542}
4543
4544
4545// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4546static const effect_uuid_t VISUALIZATION_UUID_ =
4547 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4548
4549sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4550 effect_descriptor_t *pDesc,
4551 const sp<IEffectClient>& effectClient,
4552 int32_t priority,
4553 int output,
4554 int sessionId,
4555 status_t *status,
4556 int *id,
4557 int *enabled)
4558{
4559 status_t lStatus = NO_ERROR;
4560 sp<EffectHandle> handle;
4561 effect_interface_t itfe;
4562 effect_descriptor_t desc;
4563 sp<Client> client;
4564 wp<Client> wclient;
4565
Eric Laurentde070132010-07-13 04:45:46 -07004566 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d",
4567 pid, effectClient.get(), priority, sessionId, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568
4569 if (pDesc == NULL) {
4570 lStatus = BAD_VALUE;
4571 goto Exit;
4572 }
4573
Eric Laurent84e9a102010-09-23 16:10:16 -07004574 // check audio settings permission for global effects
4575 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX && !settingsAllowed()) {
4576 lStatus = PERMISSION_DENIED;
4577 goto Exit;
4578 }
4579
4580 // Session AudioSystem::SESSION_OUTPUT_STAGE is reserved for output stage effects
4581 // that can only be created by audio policy manager (running in same process)
4582 if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE && getpid() != pid) {
4583 lStatus = PERMISSION_DENIED;
4584 goto Exit;
4585 }
4586
4587 // check recording permission for visualizer
4588 if ((memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4589 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) &&
4590 !recordingAllowed()) {
4591 lStatus = PERMISSION_DENIED;
4592 goto Exit;
4593 }
4594
4595 if (output == 0) {
4596 if (sessionId == AudioSystem::SESSION_OUTPUT_STAGE) {
4597 // output must be specified by AudioPolicyManager when using session
4598 // AudioSystem::SESSION_OUTPUT_STAGE
4599 lStatus = BAD_VALUE;
4600 goto Exit;
4601 } else if (sessionId == AudioSystem::SESSION_OUTPUT_MIX) {
4602 // if the output returned by getOutputForEffect() is removed before we lock the
4603 // mutex below, the call to checkPlaybackThread_l(output) below will detect it
4604 // and we will exit safely
4605 output = AudioSystem::getOutputForEffect(&desc);
4606 }
4607 }
4608
Mathias Agopian65ab4712010-07-14 17:59:35 -07004609 {
4610 Mutex::Autolock _l(mLock);
4611
Mathias Agopian65ab4712010-07-14 17:59:35 -07004612
4613 if (!EffectIsNullUuid(&pDesc->uuid)) {
4614 // if uuid is specified, request effect descriptor
4615 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4616 if (lStatus < 0) {
4617 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4618 goto Exit;
4619 }
4620 } else {
4621 // if uuid is not specified, look for an available implementation
4622 // of the required type in effect factory
4623 if (EffectIsNullUuid(&pDesc->type)) {
4624 LOGW("createEffect() no effect type");
4625 lStatus = BAD_VALUE;
4626 goto Exit;
4627 }
4628 uint32_t numEffects = 0;
4629 effect_descriptor_t d;
4630 bool found = false;
4631
4632 lStatus = EffectQueryNumberEffects(&numEffects);
4633 if (lStatus < 0) {
4634 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4635 goto Exit;
4636 }
4637 for (uint32_t i = 0; i < numEffects; i++) {
4638 lStatus = EffectQueryEffect(i, &desc);
4639 if (lStatus < 0) {
4640 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
4641 continue;
4642 }
4643 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4644 // If matching type found save effect descriptor. If the session is
4645 // 0 and the effect is not auxiliary, continue enumeration in case
4646 // an auxiliary version of this effect type is available
4647 found = true;
4648 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Eric Laurentde070132010-07-13 04:45:46 -07004649 if (sessionId != AudioSystem::SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004650 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4651 break;
4652 }
4653 }
4654 }
4655 if (!found) {
4656 lStatus = BAD_VALUE;
4657 LOGW("createEffect() effect not found");
4658 goto Exit;
4659 }
4660 // For same effect type, chose auxiliary version over insert version if
4661 // connect to output mix (Compliance to OpenSL ES)
Eric Laurentde070132010-07-13 04:45:46 -07004662 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004663 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4664 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4665 }
4666 }
4667
4668 // Do not allow auxiliary effects on a session different from 0 (output mix)
Eric Laurentde070132010-07-13 04:45:46 -07004669 if (sessionId != AudioSystem::SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004670 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4671 lStatus = INVALID_OPERATION;
4672 goto Exit;
4673 }
4674
Mathias Agopian65ab4712010-07-14 17:59:35 -07004675 // return effect descriptor
4676 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4677
4678 // If output is not specified try to find a matching audio session ID in one of the
4679 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07004680 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4681 // because of code checking output when entering the function.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004682 if (output == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004683 // look for the thread where the specified audio session is present
4684 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4685 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
4686 output = mPlaybackThreads.keyAt(i);
4687 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07004688 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004689 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004690 // If no output thread contains the requested session ID, default to
4691 // first output. The effect chain will be moved to the correct output
4692 // thread when a track with the same session ID is created
4693 if (output == 0 && mPlaybackThreads.size()) {
4694 output = mPlaybackThreads.keyAt(0);
4695 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004696 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004697 LOGV("createEffect() got output %d for effect %s", output, desc.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004698 PlaybackThread *thread = checkPlaybackThread_l(output);
4699 if (thread == NULL) {
Eric Laurentde070132010-07-13 04:45:46 -07004700 LOGE("createEffect() unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004701 lStatus = BAD_VALUE;
4702 goto Exit;
4703 }
4704
Eric Laurent84e9a102010-09-23 16:10:16 -07004705 // TODO: allow attachment of effect to inputs
4706
Mathias Agopian65ab4712010-07-14 17:59:35 -07004707 wclient = mClients.valueFor(pid);
4708
4709 if (wclient != NULL) {
4710 client = wclient.promote();
4711 } else {
4712 client = new Client(this, pid);
4713 mClients.add(pid, client);
4714 }
4715
4716 // create effect on selected output trhead
Eric Laurentde070132010-07-13 04:45:46 -07004717 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4718 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004719 if (handle != 0 && id != NULL) {
4720 *id = handle->id();
4721 }
4722 }
4723
4724Exit:
4725 if(status) {
4726 *status = lStatus;
4727 }
4728 return handle;
4729}
4730
Eric Laurentde070132010-07-13 04:45:46 -07004731status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
4732{
4733 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
4734 session, srcOutput, dstOutput);
4735 Mutex::Autolock _l(mLock);
4736 if (srcOutput == dstOutput) {
4737 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
4738 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004739 }
Eric Laurentde070132010-07-13 04:45:46 -07004740 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4741 if (srcThread == NULL) {
4742 LOGW("moveEffects() bad srcOutput %d", srcOutput);
4743 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004744 }
Eric Laurentde070132010-07-13 04:45:46 -07004745 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4746 if (dstThread == NULL) {
4747 LOGW("moveEffects() bad dstOutput %d", dstOutput);
4748 return BAD_VALUE;
4749 }
4750
4751 Mutex::Autolock _dl(dstThread->mLock);
4752 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07004753 moveEffectChain_l(session, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07004754
Mathias Agopian65ab4712010-07-14 17:59:35 -07004755 return NO_ERROR;
4756}
4757
Eric Laurentde070132010-07-13 04:45:46 -07004758// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
4759status_t AudioFlinger::moveEffectChain_l(int session,
4760 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07004761 AudioFlinger::PlaybackThread *dstThread,
4762 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07004763{
4764 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
4765 session, srcThread, dstThread);
4766
4767 sp<EffectChain> chain = srcThread->getEffectChain_l(session);
4768 if (chain == 0) {
4769 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
4770 session, srcThread);
4771 return INVALID_OPERATION;
4772 }
4773
Eric Laurent39e94f82010-07-28 01:32:47 -07004774 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07004775 // so that a new chain is created with correct parameters when first effect is added. This is
4776 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
4777 // removed.
4778 srcThread->removeEffectChain_l(chain);
4779
4780 // transfer all effects one by one so that new effect chain is created on new thread with
4781 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07004782 int dstOutput = dstThread->id();
4783 sp<EffectChain> dstChain;
4784 uint32_t strategy;
Eric Laurentde070132010-07-13 04:45:46 -07004785 sp<EffectModule> effect = chain->getEffectFromId_l(0);
4786 while (effect != 0) {
4787 srcThread->removeEffect_l(effect);
4788 dstThread->addEffect_l(effect);
Eric Laurent39e94f82010-07-28 01:32:47 -07004789 // if the move request is not received from audio policy manager, the effect must be
4790 // re-registered with the new strategy and output
4791 if (dstChain == 0) {
4792 dstChain = effect->chain().promote();
4793 if (dstChain == 0) {
4794 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
4795 srcThread->addEffect_l(effect);
4796 return NO_INIT;
4797 }
4798 strategy = dstChain->strategy();
4799 }
4800 if (reRegister) {
4801 AudioSystem::unregisterEffect(effect->id());
4802 AudioSystem::registerEffect(&effect->desc(),
4803 dstOutput,
4804 strategy,
4805 session,
4806 effect->id());
4807 }
Eric Laurentde070132010-07-13 04:45:46 -07004808 effect = chain->getEffectFromId_l(0);
4809 }
4810
4811 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004812}
4813
4814// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4815sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4816 const sp<AudioFlinger::Client>& client,
4817 const sp<IEffectClient>& effectClient,
4818 int32_t priority,
4819 int sessionId,
4820 effect_descriptor_t *desc,
4821 int *enabled,
4822 status_t *status
4823 )
4824{
4825 sp<EffectModule> effect;
4826 sp<EffectHandle> handle;
4827 status_t lStatus;
4828 sp<Track> track;
4829 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07004830 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004831 bool effectCreated = false;
4832 bool effectRegistered = false;
4833
4834 if (mOutput == 0) {
4835 LOGW("createEffect_l() Audio driver not initialized.");
4836 lStatus = NO_INIT;
4837 goto Exit;
4838 }
4839
4840 // Do not allow auxiliary effect on session other than 0
4841 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
Eric Laurentde070132010-07-13 04:45:46 -07004842 sessionId != AudioSystem::SESSION_OUTPUT_MIX) {
4843 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4844 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004845 lStatus = BAD_VALUE;
4846 goto Exit;
4847 }
4848
4849 // Do not allow effects with session ID 0 on direct output or duplicating threads
4850 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Eric Laurentde070132010-07-13 04:45:46 -07004851 if (sessionId == AudioSystem::SESSION_OUTPUT_MIX && mType != MIXER) {
4852 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4853 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004854 lStatus = BAD_VALUE;
4855 goto Exit;
4856 }
4857
4858 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4859
4860 { // scope for mLock
4861 Mutex::Autolock _l(mLock);
4862
4863 // check for existing effect chain with the requested audio session
4864 chain = getEffectChain_l(sessionId);
4865 if (chain == 0) {
4866 // create a new chain for this session
4867 LOGV("createEffect_l() new effect chain for session %d", sessionId);
4868 chain = new EffectChain(this, sessionId);
4869 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07004870 chain->setStrategy(getStrategyForSession_l(sessionId));
4871 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004872 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07004873 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004874 }
4875
4876 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
4877
4878 if (effect == 0) {
Eric Laurentf5aafb22010-11-18 08:40:16 -08004879 int id = mAudioFlinger->nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004880 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07004881 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004882 if (lStatus != NO_ERROR) {
4883 goto Exit;
4884 }
4885 effectRegistered = true;
4886 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07004887 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004888 lStatus = effect->status();
4889 if (lStatus != NO_ERROR) {
4890 goto Exit;
4891 }
Eric Laurentcab11242010-07-15 12:50:15 -07004892 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004893 if (lStatus != NO_ERROR) {
4894 goto Exit;
4895 }
4896 effectCreated = true;
4897
4898 effect->setDevice(mDevice);
4899 effect->setMode(mAudioFlinger->getMode());
4900 }
4901 // create effect handle and connect it to effect module
4902 handle = new EffectHandle(effect, client, effectClient, priority);
4903 lStatus = effect->addHandle(handle);
4904 if (enabled) {
4905 *enabled = (int)effect->isEnabled();
4906 }
4907 }
4908
4909Exit:
4910 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07004911 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004912 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07004913 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004914 }
4915 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07004916 AudioSystem::unregisterEffect(effect->id());
4917 }
4918 if (chainCreated) {
4919 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004920 }
4921 handle.clear();
4922 }
4923
4924 if(status) {
4925 *status = lStatus;
4926 }
4927 return handle;
4928}
4929
Eric Laurentde070132010-07-13 04:45:46 -07004930// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
4931// PlaybackThread::mLock held
4932status_t AudioFlinger::PlaybackThread::addEffect_l(const sp<EffectModule>& effect)
4933{
4934 // check for existing effect chain with the requested audio session
4935 int sessionId = effect->sessionId();
4936 sp<EffectChain> chain = getEffectChain_l(sessionId);
4937 bool chainCreated = false;
4938
4939 if (chain == 0) {
4940 // create a new chain for this session
4941 LOGV("addEffect_l() new effect chain for session %d", sessionId);
4942 chain = new EffectChain(this, sessionId);
4943 addEffectChain_l(chain);
4944 chain->setStrategy(getStrategyForSession_l(sessionId));
4945 chainCreated = true;
4946 }
4947 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
4948
4949 if (chain->getEffectFromId_l(effect->id()) != 0) {
4950 LOGW("addEffect_l() %p effect %s already present in chain %p",
4951 this, effect->desc().name, chain.get());
4952 return BAD_VALUE;
4953 }
4954
4955 status_t status = chain->addEffect_l(effect);
4956 if (status != NO_ERROR) {
4957 if (chainCreated) {
4958 removeEffectChain_l(chain);
4959 }
4960 return status;
4961 }
4962
4963 effect->setDevice(mDevice);
4964 effect->setMode(mAudioFlinger->getMode());
4965 return NO_ERROR;
4966}
4967
4968void AudioFlinger::PlaybackThread::removeEffect_l(const sp<EffectModule>& effect) {
4969
4970 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004971 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07004972 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4973 detachAuxEffect_l(effect->id());
4974 }
4975
4976 sp<EffectChain> chain = effect->chain().promote();
4977 if (chain != 0) {
4978 // remove effect chain if removing last effect
4979 if (chain->removeEffect_l(effect) == 0) {
4980 removeEffectChain_l(chain);
4981 }
4982 } else {
4983 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
4984 }
4985}
4986
4987void AudioFlinger::PlaybackThread::disconnectEffect(const sp<EffectModule>& effect,
4988 const wp<EffectHandle>& handle) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004989 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07004990 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004991 // delete the effect module if removing last handle on it
4992 if (effect->removeHandle(handle) == 0) {
Eric Laurentde070132010-07-13 04:45:46 -07004993 removeEffect_l(effect);
4994 AudioSystem::unregisterEffect(effect->id());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004995 }
4996}
4997
4998status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
4999{
5000 int session = chain->sessionId();
5001 int16_t *buffer = mMixBuffer;
5002 bool ownsBuffer = false;
5003
5004 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5005 if (session > 0) {
5006 // Only one effect chain can be present in direct output thread and it uses
5007 // the mix buffer as input
5008 if (mType != DIRECT) {
5009 size_t numSamples = mFrameCount * mChannelCount;
5010 buffer = new int16_t[numSamples];
5011 memset(buffer, 0, numSamples * sizeof(int16_t));
5012 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5013 ownsBuffer = true;
5014 }
5015
5016 // Attach all tracks with same session ID to this chain.
5017 for (size_t i = 0; i < mTracks.size(); ++i) {
5018 sp<Track> track = mTracks[i];
5019 if (session == track->sessionId()) {
5020 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5021 track->setMainBuffer(buffer);
5022 }
5023 }
5024
5025 // indicate all active tracks in the chain
5026 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5027 sp<Track> track = mActiveTracks[i].promote();
5028 if (track == 0) continue;
5029 if (session == track->sessionId()) {
5030 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
5031 chain->startTrack();
5032 }
5033 }
5034 }
5035
5036 chain->setInBuffer(buffer, ownsBuffer);
5037 chain->setOutBuffer(mMixBuffer);
Eric Laurentde070132010-07-13 04:45:46 -07005038 // Effect chain for session AudioSystem::SESSION_OUTPUT_STAGE is inserted at end of effect
5039 // chains list in order to be processed last as it contains output stage effects
5040 // Effect chain for session AudioSystem::SESSION_OUTPUT_MIX is inserted before
5041 // session AudioSystem::SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005042 // after track specific effects and before output stage
Eric Laurentde070132010-07-13 04:45:46 -07005043 // It is therefore mandatory that AudioSystem::SESSION_OUTPUT_MIX == 0 and
5044 // that AudioSystem::SESSION_OUTPUT_STAGE < AudioSystem::SESSION_OUTPUT_MIX
5045 // Effect chain for other sessions are inserted at beginning of effect
5046 // chains list to be processed before output mix effects. Relative order between other
5047 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005048 size_t size = mEffectChains.size();
5049 size_t i = 0;
5050 for (i = 0; i < size; i++) {
5051 if (mEffectChains[i]->sessionId() < session) break;
5052 }
5053 mEffectChains.insertAt(chain, i);
5054
5055 return NO_ERROR;
5056}
5057
5058size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5059{
5060 int session = chain->sessionId();
5061
5062 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5063
5064 for (size_t i = 0; i < mEffectChains.size(); i++) {
5065 if (chain == mEffectChains[i]) {
5066 mEffectChains.removeAt(i);
5067 // detach all tracks with same session ID from this chain
5068 for (size_t i = 0; i < mTracks.size(); ++i) {
5069 sp<Track> track = mTracks[i];
5070 if (session == track->sessionId()) {
5071 track->setMainBuffer(mMixBuffer);
5072 }
5073 }
Eric Laurentde070132010-07-13 04:45:46 -07005074 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005075 }
5076 }
5077 return mEffectChains.size();
5078}
5079
Eric Laurentde070132010-07-13 04:45:46 -07005080void AudioFlinger::PlaybackThread::lockEffectChains_l(
5081 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005082{
Eric Laurentde070132010-07-13 04:45:46 -07005083 effectChains = mEffectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005084 for (size_t i = 0; i < mEffectChains.size(); i++) {
5085 mEffectChains[i]->lock();
5086 }
5087}
5088
Eric Laurentde070132010-07-13 04:45:46 -07005089void AudioFlinger::PlaybackThread::unlockEffectChains(
5090 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005091{
Eric Laurentde070132010-07-13 04:45:46 -07005092 for (size_t i = 0; i < effectChains.size(); i++) {
5093 effectChains[i]->unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005094 }
5095}
5096
Eric Laurentde070132010-07-13 04:45:46 -07005097
Mathias Agopian65ab4712010-07-14 17:59:35 -07005098sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
5099{
5100 sp<EffectModule> effect;
5101
5102 sp<EffectChain> chain = getEffectChain_l(sessionId);
5103 if (chain != 0) {
Eric Laurentcab11242010-07-15 12:50:15 -07005104 effect = chain->getEffectFromId_l(effectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005105 }
5106 return effect;
5107}
5108
Eric Laurentde070132010-07-13 04:45:46 -07005109status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5110 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005111{
5112 Mutex::Autolock _l(mLock);
5113 return attachAuxEffect_l(track, EffectId);
5114}
5115
Eric Laurentde070132010-07-13 04:45:46 -07005116status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5117 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005118{
5119 status_t status = NO_ERROR;
5120
5121 if (EffectId == 0) {
5122 track->setAuxBuffer(0, NULL);
5123 } else {
Eric Laurentde070132010-07-13 04:45:46 -07005124 // Auxiliary effects are always in audio session AudioSystem::SESSION_OUTPUT_MIX
5125 sp<EffectModule> effect = getEffect_l(AudioSystem::SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005126 if (effect != 0) {
5127 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5128 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5129 } else {
5130 status = INVALID_OPERATION;
5131 }
5132 } else {
5133 status = BAD_VALUE;
5134 }
5135 }
5136 return status;
5137}
5138
5139void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5140{
5141 for (size_t i = 0; i < mTracks.size(); ++i) {
5142 sp<Track> track = mTracks[i];
5143 if (track->auxEffectId() == effectId) {
5144 attachAuxEffect_l(track, 0);
5145 }
5146 }
5147}
5148
5149// ----------------------------------------------------------------------------
5150// EffectModule implementation
5151// ----------------------------------------------------------------------------
5152
5153#undef LOG_TAG
5154#define LOG_TAG "AudioFlinger::EffectModule"
5155
5156AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5157 const wp<AudioFlinger::EffectChain>& chain,
5158 effect_descriptor_t *desc,
5159 int id,
5160 int sessionId)
5161 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5162 mStatus(NO_INIT), mState(IDLE)
5163{
5164 LOGV("Constructor %p", this);
5165 int lStatus;
5166 sp<ThreadBase> thread = mThread.promote();
5167 if (thread == 0) {
5168 return;
5169 }
5170 PlaybackThread *p = (PlaybackThread *)thread.get();
5171
5172 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5173
5174 // create effect engine from effect factory
5175 mStatus = EffectCreate(&desc->uuid, sessionId, p->id(), &mEffectInterface);
5176
5177 if (mStatus != NO_ERROR) {
5178 return;
5179 }
5180 lStatus = init();
5181 if (lStatus < 0) {
5182 mStatus = lStatus;
5183 goto Error;
5184 }
5185
5186 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5187 return;
5188Error:
5189 EffectRelease(mEffectInterface);
5190 mEffectInterface = NULL;
5191 LOGV("Constructor Error %d", mStatus);
5192}
5193
5194AudioFlinger::EffectModule::~EffectModule()
5195{
5196 LOGV("Destructor %p", this);
5197 if (mEffectInterface != NULL) {
5198 // release effect engine
5199 EffectRelease(mEffectInterface);
5200 }
5201}
5202
5203status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5204{
5205 status_t status;
5206
5207 Mutex::Autolock _l(mLock);
5208 // First handle in mHandles has highest priority and controls the effect module
5209 int priority = handle->priority();
5210 size_t size = mHandles.size();
5211 sp<EffectHandle> h;
5212 size_t i;
5213 for (i = 0; i < size; i++) {
5214 h = mHandles[i].promote();
5215 if (h == 0) continue;
5216 if (h->priority() <= priority) break;
5217 }
5218 // if inserted in first place, move effect control from previous owner to this handle
5219 if (i == 0) {
5220 if (h != 0) {
5221 h->setControl(false, true);
5222 }
5223 handle->setControl(true, false);
5224 status = NO_ERROR;
5225 } else {
5226 status = ALREADY_EXISTS;
5227 }
5228 mHandles.insertAt(handle, i);
5229 return status;
5230}
5231
5232size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5233{
5234 Mutex::Autolock _l(mLock);
5235 size_t size = mHandles.size();
5236 size_t i;
5237 for (i = 0; i < size; i++) {
5238 if (mHandles[i] == handle) break;
5239 }
5240 if (i == size) {
5241 return size;
5242 }
5243 mHandles.removeAt(i);
5244 size = mHandles.size();
5245 // if removed from first place, move effect control from this handle to next in line
5246 if (i == 0 && size != 0) {
5247 sp<EffectHandle> h = mHandles[0].promote();
5248 if (h != 0) {
5249 h->setControl(true, true);
5250 }
5251 }
5252
Eric Laurentdac69112010-09-28 14:09:57 -07005253 // Release effect engine here so that it is done immediately. Otherwise it will be released
5254 // by the destructor when the last strong reference on the this object is released which can
5255 // happen after next process is called on this effect.
5256 if (size == 0 && mEffectInterface != NULL) {
5257 // release effect engine
5258 EffectRelease(mEffectInterface);
5259 mEffectInterface = NULL;
5260 }
5261
Mathias Agopian65ab4712010-07-14 17:59:35 -07005262 return size;
5263}
5264
5265void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5266{
5267 // keep a strong reference on this EffectModule to avoid calling the
5268 // destructor before we exit
5269 sp<EffectModule> keep(this);
5270 {
5271 sp<ThreadBase> thread = mThread.promote();
5272 if (thread != 0) {
5273 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5274 playbackThread->disconnectEffect(keep, handle);
5275 }
5276 }
5277}
5278
5279void AudioFlinger::EffectModule::updateState() {
5280 Mutex::Autolock _l(mLock);
5281
5282 switch (mState) {
5283 case RESTART:
5284 reset_l();
5285 // FALL THROUGH
5286
5287 case STARTING:
5288 // clear auxiliary effect input buffer for next accumulation
5289 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5290 memset(mConfig.inputCfg.buffer.raw,
5291 0,
5292 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5293 }
5294 start_l();
5295 mState = ACTIVE;
5296 break;
5297 case STOPPING:
5298 stop_l();
5299 mDisableWaitCnt = mMaxDisableWaitCnt;
5300 mState = STOPPED;
5301 break;
5302 case STOPPED:
5303 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5304 // turn off sequence.
5305 if (--mDisableWaitCnt == 0) {
5306 reset_l();
5307 mState = IDLE;
5308 }
5309 break;
5310 default: //IDLE , ACTIVE
5311 break;
5312 }
5313}
5314
5315void AudioFlinger::EffectModule::process()
5316{
5317 Mutex::Autolock _l(mLock);
5318
5319 if (mEffectInterface == NULL ||
5320 mConfig.inputCfg.buffer.raw == NULL ||
5321 mConfig.outputCfg.buffer.raw == NULL) {
5322 return;
5323 }
5324
Eric Laurent8f45bd72010-08-31 13:50:07 -07005325 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005326 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5327 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5328 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5329 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07005330 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005331 }
5332
5333 // do the actual processing in the effect engine
5334 int ret = (*mEffectInterface)->process(mEffectInterface,
5335 &mConfig.inputCfg.buffer,
5336 &mConfig.outputCfg.buffer);
5337
5338 // force transition to IDLE state when engine is ready
5339 if (mState == STOPPED && ret == -ENODATA) {
5340 mDisableWaitCnt = 1;
5341 }
5342
5343 // clear auxiliary effect input buffer for next accumulation
5344 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08005345 memset(mConfig.inputCfg.buffer.raw, 0,
5346 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005347 }
5348 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08005349 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5350 // If an insert effect is idle and input buffer is different from output buffer,
5351 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07005352 sp<EffectChain> chain = mChain.promote();
5353 if (chain != 0 && chain->activeTracks() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08005354 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
5355 int16_t *in = mConfig.inputCfg.buffer.s16;
5356 int16_t *out = mConfig.outputCfg.buffer.s16;
5357 for (size_t i = 0; i < frameCnt; i++) {
5358 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005359 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005360 }
5361 }
5362}
5363
5364void AudioFlinger::EffectModule::reset_l()
5365{
5366 if (mEffectInterface == NULL) {
5367 return;
5368 }
5369 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5370}
5371
5372status_t AudioFlinger::EffectModule::configure()
5373{
5374 uint32_t channels;
5375 if (mEffectInterface == NULL) {
5376 return NO_INIT;
5377 }
5378
5379 sp<ThreadBase> thread = mThread.promote();
5380 if (thread == 0) {
5381 return DEAD_OBJECT;
5382 }
5383
5384 // TODO: handle configuration of effects replacing track process
5385 if (thread->channelCount() == 1) {
5386 channels = CHANNEL_MONO;
5387 } else {
5388 channels = CHANNEL_STEREO;
5389 }
5390
5391 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5392 mConfig.inputCfg.channels = CHANNEL_MONO;
5393 } else {
5394 mConfig.inputCfg.channels = channels;
5395 }
5396 mConfig.outputCfg.channels = channels;
5397 mConfig.inputCfg.format = SAMPLE_FORMAT_PCM_S15;
5398 mConfig.outputCfg.format = SAMPLE_FORMAT_PCM_S15;
5399 mConfig.inputCfg.samplingRate = thread->sampleRate();
5400 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5401 mConfig.inputCfg.bufferProvider.cookie = NULL;
5402 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5403 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5404 mConfig.outputCfg.bufferProvider.cookie = NULL;
5405 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5406 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5407 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5408 // Insert effect:
Eric Laurentde070132010-07-13 04:45:46 -07005409 // - in session AudioSystem::SESSION_OUTPUT_MIX or AudioSystem::SESSION_OUTPUT_STAGE,
5410 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07005411 // - in other sessions:
5412 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5413 // other effect: overwrites output buffer: input buffer == output buffer
5414 // Auxiliary effect:
5415 // accumulates in output buffer: input buffer != output buffer
5416 // Therefore: accumulate <=> input buffer != output buffer
5417 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5418 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5419 } else {
5420 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5421 }
5422 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5423 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5424 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5425 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5426
Eric Laurentde070132010-07-13 04:45:46 -07005427 LOGV("configure() %p thread %p buffer %p framecount %d",
5428 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5429
Mathias Agopian65ab4712010-07-14 17:59:35 -07005430 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005431 uint32_t size = sizeof(int);
5432 status_t status = (*mEffectInterface)->command(mEffectInterface,
5433 EFFECT_CMD_CONFIGURE,
5434 sizeof(effect_config_t),
5435 &mConfig,
5436 &size,
5437 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005438 if (status == 0) {
5439 status = cmdStatus;
5440 }
5441
5442 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5443 (1000 * mConfig.outputCfg.buffer.frameCount);
5444
5445 return status;
5446}
5447
5448status_t AudioFlinger::EffectModule::init()
5449{
5450 Mutex::Autolock _l(mLock);
5451 if (mEffectInterface == NULL) {
5452 return NO_INIT;
5453 }
5454 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005455 uint32_t size = sizeof(status_t);
5456 status_t status = (*mEffectInterface)->command(mEffectInterface,
5457 EFFECT_CMD_INIT,
5458 0,
5459 NULL,
5460 &size,
5461 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005462 if (status == 0) {
5463 status = cmdStatus;
5464 }
5465 return status;
5466}
5467
5468status_t AudioFlinger::EffectModule::start_l()
5469{
5470 if (mEffectInterface == NULL) {
5471 return NO_INIT;
5472 }
5473 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005474 uint32_t size = sizeof(status_t);
5475 status_t status = (*mEffectInterface)->command(mEffectInterface,
5476 EFFECT_CMD_ENABLE,
5477 0,
5478 NULL,
5479 &size,
5480 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005481 if (status == 0) {
5482 status = cmdStatus;
5483 }
5484 return status;
5485}
5486
5487status_t AudioFlinger::EffectModule::stop_l()
5488{
5489 if (mEffectInterface == NULL) {
5490 return NO_INIT;
5491 }
5492 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005493 uint32_t size = sizeof(status_t);
5494 status_t status = (*mEffectInterface)->command(mEffectInterface,
5495 EFFECT_CMD_DISABLE,
5496 0,
5497 NULL,
5498 &size,
5499 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005500 if (status == 0) {
5501 status = cmdStatus;
5502 }
5503 return status;
5504}
5505
Eric Laurent25f43952010-07-28 05:40:18 -07005506status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
5507 uint32_t cmdSize,
5508 void *pCmdData,
5509 uint32_t *replySize,
5510 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005511{
5512 Mutex::Autolock _l(mLock);
5513// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
5514
5515 if (mEffectInterface == NULL) {
5516 return NO_INIT;
5517 }
Eric Laurent25f43952010-07-28 05:40:18 -07005518 status_t status = (*mEffectInterface)->command(mEffectInterface,
5519 cmdCode,
5520 cmdSize,
5521 pCmdData,
5522 replySize,
5523 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005524 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07005525 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005526 for (size_t i = 1; i < mHandles.size(); i++) {
5527 sp<EffectHandle> h = mHandles[i].promote();
5528 if (h != 0) {
5529 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5530 }
5531 }
5532 }
5533 return status;
5534}
5535
5536status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5537{
5538 Mutex::Autolock _l(mLock);
5539 LOGV("setEnabled %p enabled %d", this, enabled);
5540
5541 if (enabled != isEnabled()) {
5542 switch (mState) {
5543 // going from disabled to enabled
5544 case IDLE:
5545 mState = STARTING;
5546 break;
5547 case STOPPED:
5548 mState = RESTART;
5549 break;
5550 case STOPPING:
5551 mState = ACTIVE;
5552 break;
5553
5554 // going from enabled to disabled
5555 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07005556 mState = STOPPED;
5557 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005558 case STARTING:
5559 mState = IDLE;
5560 break;
5561 case ACTIVE:
5562 mState = STOPPING;
5563 break;
5564 }
5565 for (size_t i = 1; i < mHandles.size(); i++) {
5566 sp<EffectHandle> h = mHandles[i].promote();
5567 if (h != 0) {
5568 h->setEnabled(enabled);
5569 }
5570 }
5571 }
5572 return NO_ERROR;
5573}
5574
5575bool AudioFlinger::EffectModule::isEnabled()
5576{
5577 switch (mState) {
5578 case RESTART:
5579 case STARTING:
5580 case ACTIVE:
5581 return true;
5582 case IDLE:
5583 case STOPPING:
5584 case STOPPED:
5585 default:
5586 return false;
5587 }
5588}
5589
Eric Laurent8f45bd72010-08-31 13:50:07 -07005590bool AudioFlinger::EffectModule::isProcessEnabled()
5591{
5592 switch (mState) {
5593 case RESTART:
5594 case ACTIVE:
5595 case STOPPING:
5596 case STOPPED:
5597 return true;
5598 case IDLE:
5599 case STARTING:
5600 default:
5601 return false;
5602 }
5603}
5604
Mathias Agopian65ab4712010-07-14 17:59:35 -07005605status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5606{
5607 Mutex::Autolock _l(mLock);
5608 status_t status = NO_ERROR;
5609
5610 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5611 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07005612 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07005613 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
5614 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005615 status_t cmdStatus;
5616 uint32_t volume[2];
5617 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07005618 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005619 volume[0] = *left;
5620 volume[1] = *right;
5621 if (controller) {
5622 pVolume = volume;
5623 }
Eric Laurent25f43952010-07-28 05:40:18 -07005624 status = (*mEffectInterface)->command(mEffectInterface,
5625 EFFECT_CMD_SET_VOLUME,
5626 size,
5627 volume,
5628 &size,
5629 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005630 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5631 *left = volume[0];
5632 *right = volume[1];
5633 }
5634 }
5635 return status;
5636}
5637
5638status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5639{
5640 Mutex::Autolock _l(mLock);
5641 status_t status = NO_ERROR;
5642 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
5643 // convert device bit field from AudioSystem to EffectApi format.
5644 device = deviceAudioSystemToEffectApi(device);
5645 if (device == 0) {
5646 return BAD_VALUE;
5647 }
5648 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005649 uint32_t size = sizeof(status_t);
5650 status = (*mEffectInterface)->command(mEffectInterface,
5651 EFFECT_CMD_SET_DEVICE,
5652 sizeof(uint32_t),
5653 &device,
5654 &size,
5655 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005656 if (status == NO_ERROR) {
5657 status = cmdStatus;
5658 }
5659 }
5660 return status;
5661}
5662
5663status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
5664{
5665 Mutex::Autolock _l(mLock);
5666 status_t status = NO_ERROR;
5667 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
5668 // convert audio mode from AudioSystem to EffectApi format.
5669 int effectMode = modeAudioSystemToEffectApi(mode);
5670 if (effectMode < 0) {
5671 return BAD_VALUE;
5672 }
5673 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005674 uint32_t size = sizeof(status_t);
5675 status = (*mEffectInterface)->command(mEffectInterface,
5676 EFFECT_CMD_SET_AUDIO_MODE,
5677 sizeof(int),
5678 &effectMode,
5679 &size,
5680 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005681 if (status == NO_ERROR) {
5682 status = cmdStatus;
5683 }
5684 }
5685 return status;
5686}
5687
5688// update this table when AudioSystem::audio_devices or audio_device_e (in EffectApi.h) are modified
5689const uint32_t AudioFlinger::EffectModule::sDeviceConvTable[] = {
5690 DEVICE_EARPIECE, // AudioSystem::DEVICE_OUT_EARPIECE
5691 DEVICE_SPEAKER, // AudioSystem::DEVICE_OUT_SPEAKER
5692 DEVICE_WIRED_HEADSET, // case AudioSystem::DEVICE_OUT_WIRED_HEADSET
5693 DEVICE_WIRED_HEADPHONE, // AudioSystem::DEVICE_OUT_WIRED_HEADPHONE
5694 DEVICE_BLUETOOTH_SCO, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO
5695 DEVICE_BLUETOOTH_SCO_HEADSET, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET
5696 DEVICE_BLUETOOTH_SCO_CARKIT, // AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT
5697 DEVICE_BLUETOOTH_A2DP, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP
5698 DEVICE_BLUETOOTH_A2DP_HEADPHONES, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES
5699 DEVICE_BLUETOOTH_A2DP_SPEAKER, // AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER
5700 DEVICE_AUX_DIGITAL // AudioSystem::DEVICE_OUT_AUX_DIGITAL
5701};
5702
5703uint32_t AudioFlinger::EffectModule::deviceAudioSystemToEffectApi(uint32_t device)
5704{
5705 uint32_t deviceOut = 0;
5706 while (device) {
5707 const uint32_t i = 31 - __builtin_clz(device);
5708 device &= ~(1 << i);
5709 if (i >= sizeof(sDeviceConvTable)/sizeof(uint32_t)) {
5710 LOGE("device convertion error for AudioSystem device 0x%08x", device);
5711 return 0;
5712 }
5713 deviceOut |= (uint32_t)sDeviceConvTable[i];
5714 }
5715 return deviceOut;
5716}
5717
5718// update this table when AudioSystem::audio_mode or audio_mode_e (in EffectApi.h) are modified
5719const uint32_t AudioFlinger::EffectModule::sModeConvTable[] = {
5720 AUDIO_MODE_NORMAL, // AudioSystem::MODE_NORMAL
5721 AUDIO_MODE_RINGTONE, // AudioSystem::MODE_RINGTONE
Jean-Michel Trivif1fb01a2010-11-15 12:11:32 -08005722 AUDIO_MODE_IN_CALL, // AudioSystem::MODE_IN_CALL
5723 AUDIO_MODE_IN_CALL // AudioSystem::MODE_IN_COMMUNICATION, same conversion as for MODE_IN_CALL
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724};
5725
5726int AudioFlinger::EffectModule::modeAudioSystemToEffectApi(uint32_t mode)
5727{
5728 int modeOut = -1;
5729 if (mode < sizeof(sModeConvTable) / sizeof(uint32_t)) {
5730 modeOut = (int)sModeConvTable[mode];
5731 }
5732 return modeOut;
5733}
5734
5735status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5736{
5737 const size_t SIZE = 256;
5738 char buffer[SIZE];
5739 String8 result;
5740
5741 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5742 result.append(buffer);
5743
5744 bool locked = tryLock(mLock);
5745 // failed to lock - AudioFlinger is probably deadlocked
5746 if (!locked) {
5747 result.append("\t\tCould not lock Fx mutex:\n");
5748 }
5749
5750 result.append("\t\tSession Status State Engine:\n");
5751 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
5752 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5753 result.append(buffer);
5754
5755 result.append("\t\tDescriptor:\n");
5756 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5757 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5758 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5759 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5760 result.append(buffer);
5761 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5762 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5763 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5764 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5765 result.append(buffer);
5766 snprintf(buffer, SIZE, "\t\t- apiVersion: %04X\n\t\t- flags: %08X\n",
5767 mDescriptor.apiVersion,
5768 mDescriptor.flags);
5769 result.append(buffer);
5770 snprintf(buffer, SIZE, "\t\t- name: %s\n",
5771 mDescriptor.name);
5772 result.append(buffer);
5773 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5774 mDescriptor.implementor);
5775 result.append(buffer);
5776
5777 result.append("\t\t- Input configuration:\n");
5778 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5779 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5780 (uint32_t)mConfig.inputCfg.buffer.raw,
5781 mConfig.inputCfg.buffer.frameCount,
5782 mConfig.inputCfg.samplingRate,
5783 mConfig.inputCfg.channels,
5784 mConfig.inputCfg.format);
5785 result.append(buffer);
5786
5787 result.append("\t\t- Output configuration:\n");
5788 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5789 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5790 (uint32_t)mConfig.outputCfg.buffer.raw,
5791 mConfig.outputCfg.buffer.frameCount,
5792 mConfig.outputCfg.samplingRate,
5793 mConfig.outputCfg.channels,
5794 mConfig.outputCfg.format);
5795 result.append(buffer);
5796
5797 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5798 result.append(buffer);
5799 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
5800 for (size_t i = 0; i < mHandles.size(); ++i) {
5801 sp<EffectHandle> handle = mHandles[i].promote();
5802 if (handle != 0) {
5803 handle->dump(buffer, SIZE);
5804 result.append(buffer);
5805 }
5806 }
5807
5808 result.append("\n");
5809
5810 write(fd, result.string(), result.length());
5811
5812 if (locked) {
5813 mLock.unlock();
5814 }
5815
5816 return NO_ERROR;
5817}
5818
5819// ----------------------------------------------------------------------------
5820// EffectHandle implementation
5821// ----------------------------------------------------------------------------
5822
5823#undef LOG_TAG
5824#define LOG_TAG "AudioFlinger::EffectHandle"
5825
5826AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5827 const sp<AudioFlinger::Client>& client,
5828 const sp<IEffectClient>& effectClient,
5829 int32_t priority)
5830 : BnEffect(),
5831 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5832{
5833 LOGV("constructor %p", this);
5834
5835 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5836 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5837 if (mCblkMemory != 0) {
5838 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5839
5840 if (mCblk) {
5841 new(mCblk) effect_param_cblk_t();
5842 mBuffer = (uint8_t *)mCblk + bufOffset;
5843 }
5844 } else {
5845 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5846 return;
5847 }
5848}
5849
5850AudioFlinger::EffectHandle::~EffectHandle()
5851{
5852 LOGV("Destructor %p", this);
5853 disconnect();
5854}
5855
5856status_t AudioFlinger::EffectHandle::enable()
5857{
5858 if (!mHasControl) return INVALID_OPERATION;
5859 if (mEffect == 0) return DEAD_OBJECT;
5860
5861 return mEffect->setEnabled(true);
5862}
5863
5864status_t AudioFlinger::EffectHandle::disable()
5865{
5866 if (!mHasControl) return INVALID_OPERATION;
5867 if (mEffect == NULL) return DEAD_OBJECT;
5868
5869 return mEffect->setEnabled(false);
5870}
5871
5872void AudioFlinger::EffectHandle::disconnect()
5873{
5874 if (mEffect == 0) {
5875 return;
5876 }
5877 mEffect->disconnect(this);
5878 // release sp on module => module destructor can be called now
5879 mEffect.clear();
5880 if (mCblk) {
5881 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
5882 }
5883 mCblkMemory.clear(); // and free the shared memory
5884 if (mClient != 0) {
5885 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
5886 mClient.clear();
5887 }
5888}
5889
Eric Laurent25f43952010-07-28 05:40:18 -07005890status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
5891 uint32_t cmdSize,
5892 void *pCmdData,
5893 uint32_t *replySize,
5894 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005895{
Eric Laurent25f43952010-07-28 05:40:18 -07005896// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
5897// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005898
5899 // only get parameter command is permitted for applications not controlling the effect
5900 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
5901 return INVALID_OPERATION;
5902 }
5903 if (mEffect == 0) return DEAD_OBJECT;
5904
5905 // handle commands that are not forwarded transparently to effect engine
5906 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
5907 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
5908 // no risk to block the whole media server process or mixer threads is we are stuck here
5909 Mutex::Autolock _l(mCblk->lock);
5910 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
5911 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
5912 mCblk->serverIndex = 0;
5913 mCblk->clientIndex = 0;
5914 return BAD_VALUE;
5915 }
5916 status_t status = NO_ERROR;
5917 while (mCblk->serverIndex < mCblk->clientIndex) {
5918 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07005919 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005920 int *p = (int *)(mBuffer + mCblk->serverIndex);
5921 int size = *p++;
5922 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
5923 LOGW("command(): invalid parameter block size");
5924 break;
5925 }
5926 effect_param_t *param = (effect_param_t *)p;
5927 if (param->psize == 0 || param->vsize == 0) {
5928 LOGW("command(): null parameter or value size");
5929 mCblk->serverIndex += size;
5930 continue;
5931 }
Eric Laurent25f43952010-07-28 05:40:18 -07005932 uint32_t psize = sizeof(effect_param_t) +
5933 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
5934 param->vsize;
5935 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
5936 psize,
5937 p,
5938 &rsize,
5939 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07005940 // stop at first error encountered
5941 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005942 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07005943 *(int *)pReplyData = reply;
5944 break;
5945 } else if (reply != NO_ERROR) {
5946 *(int *)pReplyData = reply;
5947 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 }
5949 mCblk->serverIndex += size;
5950 }
5951 mCblk->serverIndex = 0;
5952 mCblk->clientIndex = 0;
5953 return status;
5954 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07005955 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956 return enable();
5957 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07005958 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959 return disable();
5960 }
5961
5962 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5963}
5964
5965sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
5966 return mCblkMemory;
5967}
5968
5969void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
5970{
5971 LOGV("setControl %p control %d", this, hasControl);
5972
5973 mHasControl = hasControl;
5974 if (signal && mEffectClient != 0) {
5975 mEffectClient->controlStatusChanged(hasControl);
5976 }
5977}
5978
Eric Laurent25f43952010-07-28 05:40:18 -07005979void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
5980 uint32_t cmdSize,
5981 void *pCmdData,
5982 uint32_t replySize,
5983 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005984{
5985 if (mEffectClient != 0) {
5986 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5987 }
5988}
5989
5990
5991
5992void AudioFlinger::EffectHandle::setEnabled(bool enabled)
5993{
5994 if (mEffectClient != 0) {
5995 mEffectClient->enableStatusChanged(enabled);
5996 }
5997}
5998
5999status_t AudioFlinger::EffectHandle::onTransact(
6000 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6001{
6002 return BnEffect::onTransact(code, data, reply, flags);
6003}
6004
6005
6006void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6007{
6008 bool locked = tryLock(mCblk->lock);
6009
6010 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6011 (mClient == NULL) ? getpid() : mClient->pid(),
6012 mPriority,
6013 mHasControl,
6014 !locked,
6015 mCblk->clientIndex,
6016 mCblk->serverIndex
6017 );
6018
6019 if (locked) {
6020 mCblk->lock.unlock();
6021 }
6022}
6023
6024#undef LOG_TAG
6025#define LOG_TAG "AudioFlinger::EffectChain"
6026
6027AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6028 int sessionId)
Eric Laurentcab11242010-07-15 12:50:15 -07006029 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mOwnInBuffer(false),
Eric Laurent8569f0d2010-07-29 23:43:43 -07006030 mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6031 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006032{
Eric Laurentde070132010-07-13 04:45:46 -07006033 mStrategy = AudioSystem::getStrategyForStream(AudioSystem::MUSIC);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006034}
6035
6036AudioFlinger::EffectChain::~EffectChain()
6037{
6038 if (mOwnInBuffer) {
6039 delete mInBuffer;
6040 }
6041
6042}
6043
Eric Laurentcab11242010-07-15 12:50:15 -07006044// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
6045sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006046{
6047 sp<EffectModule> effect;
6048 size_t size = mEffects.size();
6049
6050 for (size_t i = 0; i < size; i++) {
6051 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6052 effect = mEffects[i];
6053 break;
6054 }
6055 }
6056 return effect;
6057}
6058
Eric Laurentcab11242010-07-15 12:50:15 -07006059// getEffectFromId_l() must be called with PlaybackThread::mLock held
6060sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006061{
6062 sp<EffectModule> effect;
6063 size_t size = mEffects.size();
6064
6065 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07006066 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6067 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006068 effect = mEffects[i];
6069 break;
6070 }
6071 }
6072 return effect;
6073}
6074
6075// Must be called with EffectChain::mLock locked
6076void AudioFlinger::EffectChain::process_l()
6077{
Eric Laurentdac69112010-09-28 14:09:57 -07006078 sp<ThreadBase> thread = mThread.promote();
6079 if (thread == 0) {
6080 LOGW("process_l(): cannot promote mixer thread");
6081 return;
6082 }
6083 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6084 bool isGlobalSession = (mSessionId == AudioSystem::SESSION_OUTPUT_MIX) ||
6085 (mSessionId == AudioSystem::SESSION_OUTPUT_STAGE);
6086 bool tracksOnSession = false;
6087 if (!isGlobalSession) {
6088 tracksOnSession =
6089 playbackThread->hasAudioSession(mSessionId) & PlaybackThread::TRACK_SESSION;
6090 }
6091
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092 size_t size = mEffects.size();
Eric Laurentdac69112010-09-28 14:09:57 -07006093 // do not process effect if no track is present in same audio session
6094 if (isGlobalSession || tracksOnSession) {
6095 for (size_t i = 0; i < size; i++) {
6096 mEffects[i]->process();
6097 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006098 }
6099 for (size_t i = 0; i < size; i++) {
6100 mEffects[i]->updateState();
6101 }
6102 // if no track is active, input buffer must be cleared here as the mixer process
6103 // will not do it
Eric Laurentdac69112010-09-28 14:09:57 -07006104 if (tracksOnSession &&
6105 activeTracks() == 0) {
6106 size_t numSamples = playbackThread->frameCount() * playbackThread->channelCount();
6107 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006108 }
6109}
6110
Eric Laurentcab11242010-07-15 12:50:15 -07006111// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07006112status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113{
6114 effect_descriptor_t desc = effect->desc();
6115 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6116
6117 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07006118 effect->setChain(this);
6119 sp<ThreadBase> thread = mThread.promote();
6120 if (thread == 0) {
6121 return NO_INIT;
6122 }
6123 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006124
6125 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6126 // Auxiliary effects are inserted at the beginning of mEffects vector as
6127 // they are processed first and accumulated in chain input buffer
6128 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07006129
Mathias Agopian65ab4712010-07-14 17:59:35 -07006130 // the input buffer for auxiliary effect contains mono samples in
6131 // 32 bit format. This is to avoid saturation in AudoMixer
6132 // accumulation stage. Saturation is done in EffectModule::process() before
6133 // calling the process in effect engine
6134 size_t numSamples = thread->frameCount();
6135 int32_t *buffer = new int32_t[numSamples];
6136 memset(buffer, 0, numSamples * sizeof(int32_t));
6137 effect->setInBuffer((int16_t *)buffer);
6138 // auxiliary effects output samples to chain input buffer for further processing
6139 // by insert effects
6140 effect->setOutBuffer(mInBuffer);
6141 } else {
6142 // Insert effects are inserted at the end of mEffects vector as they are processed
6143 // after track and auxiliary effects.
6144 // Insert effect order as a function of indicated preference:
6145 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6146 // another effect is present
6147 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6148 // last effect claiming first position
6149 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6150 // first effect claiming last position
6151 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
6152 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6153 // already present
6154
6155 int size = (int)mEffects.size();
6156 int idx_insert = size;
6157 int idx_insert_first = -1;
6158 int idx_insert_last = -1;
6159
6160 for (int i = 0; i < size; i++) {
6161 effect_descriptor_t d = mEffects[i]->desc();
6162 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6163 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6164 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6165 // check invalid effect chaining combinations
6166 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
6167 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07006168 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006169 return INVALID_OPERATION;
6170 }
6171 // remember position of first insert effect and by default
6172 // select this as insert position for new effect
6173 if (idx_insert == size) {
6174 idx_insert = i;
6175 }
6176 // remember position of last insert effect claiming
6177 // first position
6178 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6179 idx_insert_first = i;
6180 }
6181 // remember position of first insert effect claiming
6182 // last position
6183 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6184 idx_insert_last == -1) {
6185 idx_insert_last = i;
6186 }
6187 }
6188 }
6189
6190 // modify idx_insert from first position if needed
6191 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6192 if (idx_insert_last != -1) {
6193 idx_insert = idx_insert_last;
6194 } else {
6195 idx_insert = size;
6196 }
6197 } else {
6198 if (idx_insert_first != -1) {
6199 idx_insert = idx_insert_first + 1;
6200 }
6201 }
6202
6203 // always read samples from chain input buffer
6204 effect->setInBuffer(mInBuffer);
6205
6206 // if last effect in the chain, output samples to chain
6207 // output buffer, otherwise to chain input buffer
6208 if (idx_insert == size) {
6209 if (idx_insert != 0) {
6210 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6211 mEffects[idx_insert-1]->configure();
6212 }
6213 effect->setOutBuffer(mOutBuffer);
6214 } else {
6215 effect->setOutBuffer(mInBuffer);
6216 }
6217 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006218
Eric Laurentcab11242010-07-15 12:50:15 -07006219 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006220 }
6221 effect->configure();
6222 return NO_ERROR;
6223}
6224
Eric Laurentcab11242010-07-15 12:50:15 -07006225// removeEffect_l() must be called with PlaybackThread::mLock held
6226size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006227{
6228 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006229 int size = (int)mEffects.size();
6230 int i;
6231 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6232
6233 for (i = 0; i < size; i++) {
6234 if (effect == mEffects[i]) {
6235 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6236 delete[] effect->inBuffer();
6237 } else {
6238 if (i == size - 1 && i != 0) {
6239 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6240 mEffects[i - 1]->configure();
6241 }
6242 }
6243 mEffects.removeAt(i);
Eric Laurentcab11242010-07-15 12:50:15 -07006244 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006245 break;
6246 }
6247 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006248
6249 return mEffects.size();
6250}
6251
Eric Laurentcab11242010-07-15 12:50:15 -07006252// setDevice_l() must be called with PlaybackThread::mLock held
6253void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006254{
6255 size_t size = mEffects.size();
6256 for (size_t i = 0; i < size; i++) {
6257 mEffects[i]->setDevice(device);
6258 }
6259}
6260
Eric Laurentcab11242010-07-15 12:50:15 -07006261// setMode_l() must be called with PlaybackThread::mLock held
6262void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006263{
6264 size_t size = mEffects.size();
6265 for (size_t i = 0; i < size; i++) {
6266 mEffects[i]->setMode(mode);
6267 }
6268}
6269
Eric Laurentcab11242010-07-15 12:50:15 -07006270// setVolume_l() must be called with PlaybackThread::mLock held
6271bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006272{
6273 uint32_t newLeft = *left;
6274 uint32_t newRight = *right;
6275 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07006276 int ctrlIdx = -1;
6277 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006278
Eric Laurentcab11242010-07-15 12:50:15 -07006279 // first update volume controller
6280 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07006281 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07006282 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6283 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07006284 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07006285 break;
6286 }
6287 }
6288
6289 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07006290 if (hasControl) {
6291 *left = mNewLeftVolume;
6292 *right = mNewRightVolume;
6293 }
6294 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07006295 }
6296
6297 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07006298 mLeftVolume = newLeft;
6299 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006300
6301 // second get volume update from volume controller
6302 if (ctrlIdx >= 0) {
6303 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07006304 mNewLeftVolume = newLeft;
6305 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006306 }
6307 // then indicate volume to all other effects in chain.
6308 // Pass altered volume to effects before volume controller
6309 // and requested volume to effects after controller
6310 uint32_t lVol = newLeft;
6311 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006312
Mathias Agopian65ab4712010-07-14 17:59:35 -07006313 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07006314 if ((int)i == ctrlIdx) continue;
6315 // this also works for ctrlIdx == -1 when there is no volume controller
6316 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006317 lVol = *left;
6318 rVol = *right;
6319 }
6320 mEffects[i]->setVolume(&lVol, &rVol, false);
6321 }
6322 *left = newLeft;
6323 *right = newRight;
6324
6325 return hasControl;
6326}
6327
Mathias Agopian65ab4712010-07-14 17:59:35 -07006328status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6329{
6330 const size_t SIZE = 256;
6331 char buffer[SIZE];
6332 String8 result;
6333
6334 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6335 result.append(buffer);
6336
6337 bool locked = tryLock(mLock);
6338 // failed to lock - AudioFlinger is probably deadlocked
6339 if (!locked) {
6340 result.append("\tCould not lock mutex:\n");
6341 }
6342
Eric Laurentcab11242010-07-15 12:50:15 -07006343 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6344 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006345 mEffects.size(),
6346 (uint32_t)mInBuffer,
6347 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006348 mActiveTrackCnt);
6349 result.append(buffer);
6350 write(fd, result.string(), result.size());
6351
6352 for (size_t i = 0; i < mEffects.size(); ++i) {
6353 sp<EffectModule> effect = mEffects[i];
6354 if (effect != 0) {
6355 effect->dump(fd, args);
6356 }
6357 }
6358
6359 if (locked) {
6360 mLock.unlock();
6361 }
6362
6363 return NO_ERROR;
6364}
6365
6366#undef LOG_TAG
6367#define LOG_TAG "AudioFlinger"
6368
6369// ----------------------------------------------------------------------------
6370
6371status_t AudioFlinger::onTransact(
6372 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6373{
6374 return BnAudioFlinger::onTransact(code, data, reply, flags);
6375}
6376
Mathias Agopian65ab4712010-07-14 17:59:35 -07006377}; // namespace android