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