AudioFlinger.cpp revision 2b213bc220768d2b984239511cd4554a96bc0079
1/* //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/IPCThreadState.h>
28#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
34#include <utils/Atomic.h>
35
36#include <cutils/bitops.h>
37#include <cutils/properties.h>
38#include <cutils/compiler.h>
39
40#include <media/IMediaPlayerService.h>
41#include <media/IMediaDeathNotifier.h>
42
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
45
46#include <system/audio.h>
47#include <hardware/audio.h>
48
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
52#include <media/EffectsFactoryApi.h>
53#include <audio_effects/effect_visualizer.h>
54#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
56
57#include <audio_utils/primitives.h>
58
59#include <cpustats/ThreadCpuUsage.h>
60#include <powermanager/PowerManager.h>
61// #define DEBUG_CPU_USAGE 10  // log statistics every n wall clock seconds
62
63// ----------------------------------------------------------------------------
64
65
66namespace android {
67
68static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
69static const char kHardwareLockedString[] = "Hardware lock is taken\n";
70
71//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
72static const float MAX_GAIN = 4096.0f;
73static const uint32_t MAX_GAIN_INT = 0x1000;
74
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
79// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
83
84static const int kDumpLockRetries = 50;
85static const int kDumpLockSleepUs = 20000;
86
87// don't warn about blocked writes or record buffer overflows more often than this
88static const nsecs_t kWarningThrottleNs = seconds(5);
89
90// RecordThread loop sleep time upon application overrun or audio HAL read error
91static const int kRecordThreadSleepUs = 5000;
92
93// maximum time to wait for setParameters to complete
94static const nsecs_t kSetParametersTimeoutNs = seconds(2);
95
96// minimum sleep time for the mixer thread loop when tracks are active but in underrun
97static const uint32_t kMinThreadSleepTimeUs = 5000;
98// maximum divider applied to the active sleep time in the mixer thread loop
99static const uint32_t kMaxThreadSleepTimeShift = 2;
100
101
102// ----------------------------------------------------------------------------
103
104static bool recordingAllowed() {
105    if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
106    bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
107    if (!ok) ALOGE("Request requires android.permission.RECORD_AUDIO");
108    return ok;
109}
110
111static bool settingsAllowed() {
112    if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
113    bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
114    if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
115    return ok;
116}
117
118// To collect the amplifier usage
119static void addBatteryData(uint32_t params) {
120    sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
121    if (service == NULL) {
122        // it already logged
123        return;
124    }
125
126    service->addBatteryData(params);
127}
128
129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130                                audio_hw_device_t **dev)
131{
132    int rc;
133
134    rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135    if (rc)
136        goto out;
137
138    rc = audio_hw_device_open(*mod, dev);
139    ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
140            AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141    if (rc)
142        goto out;
143
144    return 0;
145
146out:
147    *mod = NULL;
148    *dev = NULL;
149    return rc;
150}
151
152static const char * const audio_interfaces[] = {
153    "primary",
154    "a2dp",
155    "usb",
156};
157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
158
159// ----------------------------------------------------------------------------
160
161AudioFlinger::AudioFlinger()
162    : BnAudioFlinger(),
163        mPrimaryHardwareDev(NULL),
164        mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
165        mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
166        mMode(AUDIO_MODE_INVALID),
167        mBtNrecIsOff(false)
168{
169}
170
171void AudioFlinger::onFirstRef()
172{
173    int rc = 0;
174
175    Mutex::Autolock _l(mLock);
176
177    /* TODO: move all this work into an Init() function */
178
179    for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
180        const hw_module_t *mod;
181        audio_hw_device_t *dev;
182
183        rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
184        if (rc)
185            continue;
186
187        ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
188             mod->name, mod->id);
189        mAudioHwDevs.push(dev);
190
191        if (mPrimaryHardwareDev == NULL) {
192            mPrimaryHardwareDev = dev;
193            ALOGI("Using '%s' (%s.%s) as the primary audio interface",
194                 mod->name, mod->id, audio_interfaces[i]);
195        }
196    }
197
198    if (mPrimaryHardwareDev == NULL) {
199        ALOGE("Primary audio interface not found");
200        // proceed, all later accesses to mPrimaryHardwareDev verify it's safe with initCheck()
201    }
202
203    // Currently (mPrimaryHardwareDev == NULL) == (mAudioHwDevs.size() == 0), but the way the
204    // primary HW dev is selected can change so these conditions might not always be equivalent.
205    // When that happens, re-visit all the code that assumes this.
206
207    AutoMutex lock(mHardwareLock);
208
209    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
210        audio_hw_device_t *dev = mAudioHwDevs[i];
211
212        mHardwareStatus = AUDIO_HW_INIT;
213        rc = dev->init_check(dev);
214        mHardwareStatus = AUDIO_HW_IDLE;
215        if (rc == 0) {
216            mMode = AUDIO_MODE_NORMAL;  // assigned multiple times with same value
217            mHardwareStatus = AUDIO_HW_SET_MODE;
218            dev->set_mode(dev, mMode);
219            mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
220            dev->set_master_volume(dev, 1.0f);
221            mHardwareStatus = AUDIO_HW_IDLE;
222        }
223    }
224}
225
226AudioFlinger::~AudioFlinger()
227{
228
229    while (!mRecordThreads.isEmpty()) {
230        // closeInput() will remove first entry from mRecordThreads
231        closeInput(mRecordThreads.keyAt(0));
232    }
233    while (!mPlaybackThreads.isEmpty()) {
234        // closeOutput() will remove first entry from mPlaybackThreads
235        closeOutput(mPlaybackThreads.keyAt(0));
236    }
237
238    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
239        // no mHardwareLock needed, as there are no other references to this
240        audio_hw_device_close(mAudioHwDevs[i]);
241    }
242}
243
244audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
245{
246    /* first matching HW device is returned */
247    for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
248        audio_hw_device_t *dev = mAudioHwDevs[i];
249        if ((dev->get_supported_devices(dev) & devices) == devices)
250            return dev;
251    }
252    return NULL;
253}
254
255status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
256{
257    const size_t SIZE = 256;
258    char buffer[SIZE];
259    String8 result;
260
261    result.append("Clients:\n");
262    for (size_t i = 0; i < mClients.size(); ++i) {
263        sp<Client> client = mClients.valueAt(i).promote();
264        if (client != 0) {
265            snprintf(buffer, SIZE, "  pid: %d\n", client->pid());
266            result.append(buffer);
267        }
268    }
269
270    result.append("Global session refs:\n");
271    result.append(" session pid cnt\n");
272    for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
273        AudioSessionRef *r = mAudioSessionRefs[i];
274        snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
275        result.append(buffer);
276    }
277    write(fd, result.string(), result.size());
278    return NO_ERROR;
279}
280
281
282status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
283{
284    const size_t SIZE = 256;
285    char buffer[SIZE];
286    String8 result;
287    hardware_call_state hardwareStatus = mHardwareStatus;
288
289    snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
290    result.append(buffer);
291    write(fd, result.string(), result.size());
292    return NO_ERROR;
293}
294
295status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
296{
297    const size_t SIZE = 256;
298    char buffer[SIZE];
299    String8 result;
300    snprintf(buffer, SIZE, "Permission Denial: "
301            "can't dump AudioFlinger from pid=%d, uid=%d\n",
302            IPCThreadState::self()->getCallingPid(),
303            IPCThreadState::self()->getCallingUid());
304    result.append(buffer);
305    write(fd, result.string(), result.size());
306    return NO_ERROR;
307}
308
309static bool tryLock(Mutex& mutex)
310{
311    bool locked = false;
312    for (int i = 0; i < kDumpLockRetries; ++i) {
313        if (mutex.tryLock() == NO_ERROR) {
314            locked = true;
315            break;
316        }
317        usleep(kDumpLockSleepUs);
318    }
319    return locked;
320}
321
322status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
323{
324    if (!checkCallingPermission(String16("android.permission.DUMP"))) {
325        dumpPermissionDenial(fd, args);
326    } else {
327        // get state of hardware lock
328        bool hardwareLocked = tryLock(mHardwareLock);
329        if (!hardwareLocked) {
330            String8 result(kHardwareLockedString);
331            write(fd, result.string(), result.size());
332        } else {
333            mHardwareLock.unlock();
334        }
335
336        bool locked = tryLock(mLock);
337
338        // failed to lock - AudioFlinger is probably deadlocked
339        if (!locked) {
340            String8 result(kDeadlockedString);
341            write(fd, result.string(), result.size());
342        }
343
344        dumpClients(fd, args);
345        dumpInternals(fd, args);
346
347        // dump playback threads
348        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
349            mPlaybackThreads.valueAt(i)->dump(fd, args);
350        }
351
352        // dump record threads
353        for (size_t i = 0; i < mRecordThreads.size(); i++) {
354            mRecordThreads.valueAt(i)->dump(fd, args);
355        }
356
357        // dump all hardware devs
358        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
359            audio_hw_device_t *dev = mAudioHwDevs[i];
360            dev->dump(dev, fd);
361        }
362        if (locked) mLock.unlock();
363    }
364    return NO_ERROR;
365}
366
367sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
368{
369    // If pid is already in the mClients wp<> map, then use that entry
370    // (for which promote() is always != 0), otherwise create a new entry and Client.
371    sp<Client> client = mClients.valueFor(pid).promote();
372    if (client == 0) {
373        client = new Client(this, pid);
374        mClients.add(pid, client);
375    }
376
377    return client;
378}
379
380// IAudioFlinger interface
381
382
383sp<IAudioTrack> AudioFlinger::createTrack(
384        pid_t pid,
385        audio_stream_type_t streamType,
386        uint32_t sampleRate,
387        audio_format_t format,
388        uint32_t channelMask,
389        int frameCount,
390        uint32_t flags,
391        const sp<IMemory>& sharedBuffer,
392        audio_io_handle_t output,
393        int *sessionId,
394        status_t *status)
395{
396    sp<PlaybackThread::Track> track;
397    sp<TrackHandle> trackHandle;
398    sp<Client> client;
399    status_t lStatus;
400    int lSessionId;
401
402    // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
403    // but if someone uses binder directly they could bypass that and cause us to crash
404    if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
405        ALOGE("createTrack() invalid stream type %d", streamType);
406        lStatus = BAD_VALUE;
407        goto Exit;
408    }
409
410    {
411        Mutex::Autolock _l(mLock);
412        PlaybackThread *thread = checkPlaybackThread_l(output);
413        PlaybackThread *effectThread = NULL;
414        if (thread == NULL) {
415            ALOGE("unknown output thread");
416            lStatus = BAD_VALUE;
417            goto Exit;
418        }
419
420        client = registerPid_l(pid);
421
422        ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
423        if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
424            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
425                sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
426                if (mPlaybackThreads.keyAt(i) != output) {
427                    // prevent same audio session on different output threads
428                    uint32_t sessions = t->hasAudioSession(*sessionId);
429                    if (sessions & PlaybackThread::TRACK_SESSION) {
430                        ALOGE("createTrack() session ID %d already in use", *sessionId);
431                        lStatus = BAD_VALUE;
432                        goto Exit;
433                    }
434                    // check if an effect with same session ID is waiting for a track to be created
435                    if (sessions & PlaybackThread::EFFECT_SESSION) {
436                        effectThread = t.get();
437                    }
438                }
439            }
440            lSessionId = *sessionId;
441        } else {
442            // if no audio session id is provided, create one here
443            lSessionId = nextUniqueId();
444            if (sessionId != NULL) {
445                *sessionId = lSessionId;
446            }
447        }
448        ALOGV("createTrack() lSessionId: %d", lSessionId);
449
450        track = thread->createTrack_l(client, streamType, sampleRate, format,
451                channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
452
453        // move effect chain to this output thread if an effect on same session was waiting
454        // for a track to be created
455        if (lStatus == NO_ERROR && effectThread != NULL) {
456            Mutex::Autolock _dl(thread->mLock);
457            Mutex::Autolock _sl(effectThread->mLock);
458            moveEffectChain_l(lSessionId, effectThread, thread, true);
459        }
460    }
461    if (lStatus == NO_ERROR) {
462        trackHandle = new TrackHandle(track);
463    } else {
464        // remove local strong reference to Client before deleting the Track so that the Client
465        // destructor is called by the TrackBase destructor with mLock held
466        client.clear();
467        track.clear();
468    }
469
470Exit:
471    if(status) {
472        *status = lStatus;
473    }
474    return trackHandle;
475}
476
477uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
478{
479    Mutex::Autolock _l(mLock);
480    PlaybackThread *thread = checkPlaybackThread_l(output);
481    if (thread == NULL) {
482        ALOGW("sampleRate() unknown thread %d", output);
483        return 0;
484    }
485    return thread->sampleRate();
486}
487
488int AudioFlinger::channelCount(audio_io_handle_t output) const
489{
490    Mutex::Autolock _l(mLock);
491    PlaybackThread *thread = checkPlaybackThread_l(output);
492    if (thread == NULL) {
493        ALOGW("channelCount() unknown thread %d", output);
494        return 0;
495    }
496    return thread->channelCount();
497}
498
499audio_format_t AudioFlinger::format(audio_io_handle_t output) const
500{
501    Mutex::Autolock _l(mLock);
502    PlaybackThread *thread = checkPlaybackThread_l(output);
503    if (thread == NULL) {
504        ALOGW("format() unknown thread %d", output);
505        return AUDIO_FORMAT_INVALID;
506    }
507    return thread->format();
508}
509
510size_t AudioFlinger::frameCount(audio_io_handle_t output) const
511{
512    Mutex::Autolock _l(mLock);
513    PlaybackThread *thread = checkPlaybackThread_l(output);
514    if (thread == NULL) {
515        ALOGW("frameCount() unknown thread %d", output);
516        return 0;
517    }
518    return thread->frameCount();
519}
520
521uint32_t AudioFlinger::latency(audio_io_handle_t output) const
522{
523    Mutex::Autolock _l(mLock);
524    PlaybackThread *thread = checkPlaybackThread_l(output);
525    if (thread == NULL) {
526        ALOGW("latency() unknown thread %d", output);
527        return 0;
528    }
529    return thread->latency();
530}
531
532status_t AudioFlinger::setMasterVolume(float value)
533{
534    status_t ret = initCheck();
535    if (ret != NO_ERROR) {
536        return ret;
537    }
538
539    // check calling permissions
540    if (!settingsAllowed()) {
541        return PERMISSION_DENIED;
542    }
543
544    // when hw supports master volume, don't scale in sw mixer
545    { // scope for the lock
546        AutoMutex lock(mHardwareLock);
547        mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
548        if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
549            value = 1.0f;
550        }
551        mHardwareStatus = AUDIO_HW_IDLE;
552    }
553
554    Mutex::Autolock _l(mLock);
555    mMasterVolume = value;
556    for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
557       mPlaybackThreads.valueAt(i)->setMasterVolume(value);
558
559    return NO_ERROR;
560}
561
562status_t AudioFlinger::setMode(audio_mode_t mode)
563{
564    status_t ret = initCheck();
565    if (ret != NO_ERROR) {
566        return ret;
567    }
568
569    // check calling permissions
570    if (!settingsAllowed()) {
571        return PERMISSION_DENIED;
572    }
573    if (uint32_t(mode) >= AUDIO_MODE_CNT) {
574        ALOGW("Illegal value: setMode(%d)", mode);
575        return BAD_VALUE;
576    }
577
578    { // scope for the lock
579        AutoMutex lock(mHardwareLock);
580        mHardwareStatus = AUDIO_HW_SET_MODE;
581        ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
582        mHardwareStatus = AUDIO_HW_IDLE;
583    }
584
585    if (NO_ERROR == ret) {
586        Mutex::Autolock _l(mLock);
587        mMode = mode;
588        for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
589           mPlaybackThreads.valueAt(i)->setMode(mode);
590    }
591
592    return ret;
593}
594
595status_t AudioFlinger::setMicMute(bool state)
596{
597    status_t ret = initCheck();
598    if (ret != NO_ERROR) {
599        return ret;
600    }
601
602    // check calling permissions
603    if (!settingsAllowed()) {
604        return PERMISSION_DENIED;
605    }
606
607    AutoMutex lock(mHardwareLock);
608    mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
609    ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
610    mHardwareStatus = AUDIO_HW_IDLE;
611    return ret;
612}
613
614bool AudioFlinger::getMicMute() const
615{
616    status_t ret = initCheck();
617    if (ret != NO_ERROR) {
618        return false;
619    }
620
621    bool state = AUDIO_MODE_INVALID;
622    AutoMutex lock(mHardwareLock);
623    mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
624    mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
625    mHardwareStatus = AUDIO_HW_IDLE;
626    return state;
627}
628
629status_t AudioFlinger::setMasterMute(bool muted)
630{
631    // check calling permissions
632    if (!settingsAllowed()) {
633        return PERMISSION_DENIED;
634    }
635
636    Mutex::Autolock _l(mLock);
637    mMasterMute = muted;
638    for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
639       mPlaybackThreads.valueAt(i)->setMasterMute(muted);
640
641    return NO_ERROR;
642}
643
644float AudioFlinger::masterVolume() const
645{
646    Mutex::Autolock _l(mLock);
647    return masterVolume_l();
648}
649
650bool AudioFlinger::masterMute() const
651{
652    Mutex::Autolock _l(mLock);
653    return masterMute_l();
654}
655
656status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
657        audio_io_handle_t output)
658{
659    // check calling permissions
660    if (!settingsAllowed()) {
661        return PERMISSION_DENIED;
662    }
663
664    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
665        ALOGE("setStreamVolume() invalid stream %d", stream);
666        return BAD_VALUE;
667    }
668
669    AutoMutex lock(mLock);
670    PlaybackThread *thread = NULL;
671    if (output) {
672        thread = checkPlaybackThread_l(output);
673        if (thread == NULL) {
674            return BAD_VALUE;
675        }
676    }
677
678    mStreamTypes[stream].volume = value;
679
680    if (thread == NULL) {
681        for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
682           mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
683        }
684    } else {
685        thread->setStreamVolume(stream, value);
686    }
687
688    return NO_ERROR;
689}
690
691status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
692{
693    // check calling permissions
694    if (!settingsAllowed()) {
695        return PERMISSION_DENIED;
696    }
697
698    if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
699        uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
700        ALOGE("setStreamMute() invalid stream %d", stream);
701        return BAD_VALUE;
702    }
703
704    AutoMutex lock(mLock);
705    mStreamTypes[stream].mute = muted;
706    for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
707       mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
708
709    return NO_ERROR;
710}
711
712float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
713{
714    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
715        return 0.0f;
716    }
717
718    AutoMutex lock(mLock);
719    float volume;
720    if (output) {
721        PlaybackThread *thread = checkPlaybackThread_l(output);
722        if (thread == NULL) {
723            return 0.0f;
724        }
725        volume = thread->streamVolume(stream);
726    } else {
727        volume = mStreamTypes[stream].volume;
728    }
729
730    return volume;
731}
732
733bool AudioFlinger::streamMute(audio_stream_type_t stream) const
734{
735    if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
736        return true;
737    }
738
739    return mStreamTypes[stream].mute;
740}
741
742status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
743{
744    status_t result;
745
746    ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
747            ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
748    // check calling permissions
749    if (!settingsAllowed()) {
750        return PERMISSION_DENIED;
751    }
752
753    // ioHandle == 0 means the parameters are global to the audio hardware interface
754    if (ioHandle == 0) {
755        AutoMutex lock(mHardwareLock);
756        mHardwareStatus = AUDIO_SET_PARAMETER;
757        status_t final_result = NO_ERROR;
758        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
759            audio_hw_device_t *dev = mAudioHwDevs[i];
760            result = dev->set_parameters(dev, keyValuePairs.string());
761            final_result = result ?: final_result;
762        }
763        mHardwareStatus = AUDIO_HW_IDLE;
764        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
765        AudioParameter param = AudioParameter(keyValuePairs);
766        String8 value;
767        if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
768            Mutex::Autolock _l(mLock);
769            bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
770            if (mBtNrecIsOff != btNrecIsOff) {
771                for (size_t i = 0; i < mRecordThreads.size(); i++) {
772                    sp<RecordThread> thread = mRecordThreads.valueAt(i);
773                    RecordThread::RecordTrack *track = thread->track();
774                    if (track != NULL) {
775                        audio_devices_t device = (audio_devices_t)(
776                                thread->device() & AUDIO_DEVICE_IN_ALL);
777                        bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
778                        thread->setEffectSuspended(FX_IID_AEC,
779                                                   suspend,
780                                                   track->sessionId());
781                        thread->setEffectSuspended(FX_IID_NS,
782                                                   suspend,
783                                                   track->sessionId());
784                    }
785                }
786                mBtNrecIsOff = btNrecIsOff;
787            }
788        }
789        return final_result;
790    }
791
792    // hold a strong ref on thread in case closeOutput() or closeInput() is called
793    // and the thread is exited once the lock is released
794    sp<ThreadBase> thread;
795    {
796        Mutex::Autolock _l(mLock);
797        thread = checkPlaybackThread_l(ioHandle);
798        if (thread == NULL) {
799            thread = checkRecordThread_l(ioHandle);
800        } else if (thread == primaryPlaybackThread_l()) {
801            // indicate output device change to all input threads for pre processing
802            AudioParameter param = AudioParameter(keyValuePairs);
803            int value;
804            if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
805                for (size_t i = 0; i < mRecordThreads.size(); i++) {
806                    mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
807                }
808            }
809        }
810    }
811    if (thread != 0) {
812        return thread->setParameters(keyValuePairs);
813    }
814    return BAD_VALUE;
815}
816
817String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
818{
819//    ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
820//            ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
821
822    if (ioHandle == 0) {
823        String8 out_s8;
824
825        for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
826            audio_hw_device_t *dev = mAudioHwDevs[i];
827            char *s = dev->get_parameters(dev, keys.string());
828            out_s8 += String8(s);
829            free(s);
830        }
831        return out_s8;
832    }
833
834    Mutex::Autolock _l(mLock);
835
836    PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
837    if (playbackThread != NULL) {
838        return playbackThread->getParameters(keys);
839    }
840    RecordThread *recordThread = checkRecordThread_l(ioHandle);
841    if (recordThread != NULL) {
842        return recordThread->getParameters(keys);
843    }
844    return String8("");
845}
846
847size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
848{
849    status_t ret = initCheck();
850    if (ret != NO_ERROR) {
851        return 0;
852    }
853
854    AutoMutex lock(mHardwareLock);
855    mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
856    size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
857    mHardwareStatus = AUDIO_HW_IDLE;
858    return size;
859}
860
861unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
862{
863    if (ioHandle == 0) {
864        return 0;
865    }
866
867    Mutex::Autolock _l(mLock);
868
869    RecordThread *recordThread = checkRecordThread_l(ioHandle);
870    if (recordThread != NULL) {
871        return recordThread->getInputFramesLost();
872    }
873    return 0;
874}
875
876status_t AudioFlinger::setVoiceVolume(float value)
877{
878    status_t ret = initCheck();
879    if (ret != NO_ERROR) {
880        return ret;
881    }
882
883    // check calling permissions
884    if (!settingsAllowed()) {
885        return PERMISSION_DENIED;
886    }
887
888    AutoMutex lock(mHardwareLock);
889    mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
890    ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
891    mHardwareStatus = AUDIO_HW_IDLE;
892
893    return ret;
894}
895
896status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
897        audio_io_handle_t output) const
898{
899    status_t status;
900
901    Mutex::Autolock _l(mLock);
902
903    PlaybackThread *playbackThread = checkPlaybackThread_l(output);
904    if (playbackThread != NULL) {
905        return playbackThread->getRenderPosition(halFrames, dspFrames);
906    }
907
908    return BAD_VALUE;
909}
910
911void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
912{
913
914    Mutex::Autolock _l(mLock);
915
916    pid_t pid = IPCThreadState::self()->getCallingPid();
917    if (mNotificationClients.indexOfKey(pid) < 0) {
918        sp<NotificationClient> notificationClient = new NotificationClient(this,
919                                                                            client,
920                                                                            pid);
921        ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
922
923        mNotificationClients.add(pid, notificationClient);
924
925        sp<IBinder> binder = client->asBinder();
926        binder->linkToDeath(notificationClient);
927
928        // the config change is always sent from playback or record threads to avoid deadlock
929        // with AudioSystem::gLock
930        for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
931            mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
932        }
933
934        for (size_t i = 0; i < mRecordThreads.size(); i++) {
935            mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
936        }
937    }
938}
939
940void AudioFlinger::removeNotificationClient(pid_t pid)
941{
942    Mutex::Autolock _l(mLock);
943
944    int index = mNotificationClients.indexOfKey(pid);
945    if (index >= 0) {
946        sp <NotificationClient> client = mNotificationClients.valueFor(pid);
947        ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
948        mNotificationClients.removeItem(pid);
949    }
950
951    ALOGV("%d died, releasing its sessions", pid);
952    int num = mAudioSessionRefs.size();
953    bool removed = false;
954    for (int i = 0; i< num; i++) {
955        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
956        ALOGV(" pid %d @ %d", ref->pid, i);
957        if (ref->pid == pid) {
958            ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
959            mAudioSessionRefs.removeAt(i);
960            delete ref;
961            removed = true;
962            i--;
963            num--;
964        }
965    }
966    if (removed) {
967        purgeStaleEffects_l();
968    }
969}
970
971// audioConfigChanged_l() must be called with AudioFlinger::mLock held
972void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, void *param2)
973{
974    size_t size = mNotificationClients.size();
975    for (size_t i = 0; i < size; i++) {
976        mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
977                                                                               param2);
978    }
979}
980
981// removeClient_l() must be called with AudioFlinger::mLock held
982void AudioFlinger::removeClient_l(pid_t pid)
983{
984    ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
985    mClients.removeItem(pid);
986}
987
988
989// ----------------------------------------------------------------------------
990
991AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
992        uint32_t device, type_t type)
993    :   Thread(false),
994        mType(type),
995        mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
996        // mChannelMask
997        mChannelCount(0),
998        mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
999        mParamStatus(NO_ERROR),
1000        mStandby(false), mId(id),
1001        mDevice(device),
1002        mDeathRecipient(new PMDeathRecipient(this))
1003{
1004}
1005
1006AudioFlinger::ThreadBase::~ThreadBase()
1007{
1008    mParamCond.broadcast();
1009    // do not lock the mutex in destructor
1010    releaseWakeLock_l();
1011    if (mPowerManager != 0) {
1012        sp<IBinder> binder = mPowerManager->asBinder();
1013        binder->unlinkToDeath(mDeathRecipient);
1014    }
1015}
1016
1017void AudioFlinger::ThreadBase::exit()
1018{
1019    ALOGV("ThreadBase::exit");
1020    {
1021        // This lock prevents the following race in thread (uniprocessor for illustration):
1022        //  if (!exitPending()) {
1023        //      // context switch from here to exit()
1024        //      // exit() calls requestExit(), what exitPending() observes
1025        //      // exit() calls signal(), which is dropped since no waiters
1026        //      // context switch back from exit() to here
1027        //      mWaitWorkCV.wait(...);
1028        //      // now thread is hung
1029        //  }
1030        AutoMutex lock(mLock);
1031        requestExit();
1032        mWaitWorkCV.signal();
1033    }
1034    // When Thread::requestExitAndWait is made virtual and this method is renamed to
1035    // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
1036    requestExitAndWait();
1037}
1038
1039status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1040{
1041    status_t status;
1042
1043    ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
1044    Mutex::Autolock _l(mLock);
1045
1046    mNewParameters.add(keyValuePairs);
1047    mWaitWorkCV.signal();
1048    // wait condition with timeout in case the thread loop has exited
1049    // before the request could be processed
1050    if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
1051        status = mParamStatus;
1052        mWaitWorkCV.signal();
1053    } else {
1054        status = TIMED_OUT;
1055    }
1056    return status;
1057}
1058
1059void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1060{
1061    Mutex::Autolock _l(mLock);
1062    sendConfigEvent_l(event, param);
1063}
1064
1065// sendConfigEvent_l() must be called with ThreadBase::mLock held
1066void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1067{
1068    ConfigEvent configEvent;
1069    configEvent.mEvent = event;
1070    configEvent.mParam = param;
1071    mConfigEvents.add(configEvent);
1072    ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1073    mWaitWorkCV.signal();
1074}
1075
1076void AudioFlinger::ThreadBase::processConfigEvents()
1077{
1078    mLock.lock();
1079    while(!mConfigEvents.isEmpty()) {
1080        ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
1081        ConfigEvent configEvent = mConfigEvents[0];
1082        mConfigEvents.removeAt(0);
1083        // release mLock before locking AudioFlinger mLock: lock order is always
1084        // AudioFlinger then ThreadBase to avoid cross deadlock
1085        mLock.unlock();
1086        mAudioFlinger->mLock.lock();
1087        audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
1088        mAudioFlinger->mLock.unlock();
1089        mLock.lock();
1090    }
1091    mLock.unlock();
1092}
1093
1094status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1095{
1096    const size_t SIZE = 256;
1097    char buffer[SIZE];
1098    String8 result;
1099
1100    bool locked = tryLock(mLock);
1101    if (!locked) {
1102        snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1103        write(fd, buffer, strlen(buffer));
1104    }
1105
1106    snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1107    result.append(buffer);
1108    snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1109    result.append(buffer);
1110    snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1111    result.append(buffer);
1112    snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1113    result.append(buffer);
1114    snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1115    result.append(buffer);
1116    snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1117    result.append(buffer);
1118    snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
1119    result.append(buffer);
1120
1121    snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1122    result.append(buffer);
1123    result.append(" Index Command");
1124    for (size_t i = 0; i < mNewParameters.size(); ++i) {
1125        snprintf(buffer, SIZE, "\n %02d    ", i);
1126        result.append(buffer);
1127        result.append(mNewParameters[i]);
1128    }
1129
1130    snprintf(buffer, SIZE, "\n\nPending config events: \n");
1131    result.append(buffer);
1132    snprintf(buffer, SIZE, " Index event param\n");
1133    result.append(buffer);
1134    for (size_t i = 0; i < mConfigEvents.size(); i++) {
1135        snprintf(buffer, SIZE, " %02d    %02d    %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
1136        result.append(buffer);
1137    }
1138    result.append("\n");
1139
1140    write(fd, result.string(), result.size());
1141
1142    if (locked) {
1143        mLock.unlock();
1144    }
1145    return NO_ERROR;
1146}
1147
1148status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1149{
1150    const size_t SIZE = 256;
1151    char buffer[SIZE];
1152    String8 result;
1153
1154    snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1155    write(fd, buffer, strlen(buffer));
1156
1157    for (size_t i = 0; i < mEffectChains.size(); ++i) {
1158        sp<EffectChain> chain = mEffectChains[i];
1159        if (chain != 0) {
1160            chain->dump(fd, args);
1161        }
1162    }
1163    return NO_ERROR;
1164}
1165
1166void AudioFlinger::ThreadBase::acquireWakeLock()
1167{
1168    Mutex::Autolock _l(mLock);
1169    acquireWakeLock_l();
1170}
1171
1172void AudioFlinger::ThreadBase::acquireWakeLock_l()
1173{
1174    if (mPowerManager == 0) {
1175        // use checkService() to avoid blocking if power service is not up yet
1176        sp<IBinder> binder =
1177            defaultServiceManager()->checkService(String16("power"));
1178        if (binder == 0) {
1179            ALOGW("Thread %s cannot connect to the power manager service", mName);
1180        } else {
1181            mPowerManager = interface_cast<IPowerManager>(binder);
1182            binder->linkToDeath(mDeathRecipient);
1183        }
1184    }
1185    if (mPowerManager != 0) {
1186        sp<IBinder> binder = new BBinder();
1187        status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1188                                                         binder,
1189                                                         String16(mName));
1190        if (status == NO_ERROR) {
1191            mWakeLockToken = binder;
1192        }
1193        ALOGV("acquireWakeLock_l() %s status %d", mName, status);
1194    }
1195}
1196
1197void AudioFlinger::ThreadBase::releaseWakeLock()
1198{
1199    Mutex::Autolock _l(mLock);
1200    releaseWakeLock_l();
1201}
1202
1203void AudioFlinger::ThreadBase::releaseWakeLock_l()
1204{
1205    if (mWakeLockToken != 0) {
1206        ALOGV("releaseWakeLock_l() %s", mName);
1207        if (mPowerManager != 0) {
1208            mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1209        }
1210        mWakeLockToken.clear();
1211    }
1212}
1213
1214void AudioFlinger::ThreadBase::clearPowerManager()
1215{
1216    Mutex::Autolock _l(mLock);
1217    releaseWakeLock_l();
1218    mPowerManager.clear();
1219}
1220
1221void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1222{
1223    sp<ThreadBase> thread = mThread.promote();
1224    if (thread != 0) {
1225        thread->clearPowerManager();
1226    }
1227    ALOGW("power manager service died !!!");
1228}
1229
1230void AudioFlinger::ThreadBase::setEffectSuspended(
1231        const effect_uuid_t *type, bool suspend, int sessionId)
1232{
1233    Mutex::Autolock _l(mLock);
1234    setEffectSuspended_l(type, suspend, sessionId);
1235}
1236
1237void AudioFlinger::ThreadBase::setEffectSuspended_l(
1238        const effect_uuid_t *type, bool suspend, int sessionId)
1239{
1240    sp<EffectChain> chain = getEffectChain_l(sessionId);
1241    if (chain != 0) {
1242        if (type != NULL) {
1243            chain->setEffectSuspended_l(type, suspend);
1244        } else {
1245            chain->setEffectSuspendedAll_l(suspend);
1246        }
1247    }
1248
1249    updateSuspendedSessions_l(type, suspend, sessionId);
1250}
1251
1252void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1253{
1254    int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1255    if (index < 0) {
1256        return;
1257    }
1258
1259    KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1260            mSuspendedSessions.editValueAt(index);
1261
1262    for (size_t i = 0; i < sessionEffects.size(); i++) {
1263        sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1264        for (int j = 0; j < desc->mRefCount; j++) {
1265            if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1266                chain->setEffectSuspendedAll_l(true);
1267            } else {
1268                ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1269                     desc->mType.timeLow);
1270                chain->setEffectSuspended_l(&desc->mType, true);
1271            }
1272        }
1273    }
1274}
1275
1276void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1277                                                         bool suspend,
1278                                                         int sessionId)
1279{
1280    int index = mSuspendedSessions.indexOfKey(sessionId);
1281
1282    KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1283
1284    if (suspend) {
1285        if (index >= 0) {
1286            sessionEffects = mSuspendedSessions.editValueAt(index);
1287        } else {
1288            mSuspendedSessions.add(sessionId, sessionEffects);
1289        }
1290    } else {
1291        if (index < 0) {
1292            return;
1293        }
1294        sessionEffects = mSuspendedSessions.editValueAt(index);
1295    }
1296
1297
1298    int key = EffectChain::kKeyForSuspendAll;
1299    if (type != NULL) {
1300        key = type->timeLow;
1301    }
1302    index = sessionEffects.indexOfKey(key);
1303
1304    sp <SuspendedSessionDesc> desc;
1305    if (suspend) {
1306        if (index >= 0) {
1307            desc = sessionEffects.valueAt(index);
1308        } else {
1309            desc = new SuspendedSessionDesc();
1310            if (type != NULL) {
1311                memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1312            }
1313            sessionEffects.add(key, desc);
1314            ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1315        }
1316        desc->mRefCount++;
1317    } else {
1318        if (index < 0) {
1319            return;
1320        }
1321        desc = sessionEffects.valueAt(index);
1322        if (--desc->mRefCount == 0) {
1323            ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1324            sessionEffects.removeItemsAt(index);
1325            if (sessionEffects.isEmpty()) {
1326                ALOGV("updateSuspendedSessions_l() restore removing session %d",
1327                                 sessionId);
1328                mSuspendedSessions.removeItem(sessionId);
1329            }
1330        }
1331    }
1332    if (!sessionEffects.isEmpty()) {
1333        mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1334    }
1335}
1336
1337void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1338                                                            bool enabled,
1339                                                            int sessionId)
1340{
1341    Mutex::Autolock _l(mLock);
1342    checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1343}
1344
1345void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1346                                                            bool enabled,
1347                                                            int sessionId)
1348{
1349    if (mType != RECORD) {
1350        // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1351        // another session. This gives the priority to well behaved effect control panels
1352        // and applications not using global effects.
1353        if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1354            setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1355        }
1356    }
1357
1358    sp<EffectChain> chain = getEffectChain_l(sessionId);
1359    if (chain != 0) {
1360        chain->checkSuspendOnEffectEnabled(effect, enabled);
1361    }
1362}
1363
1364// ----------------------------------------------------------------------------
1365
1366AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1367                                             AudioStreamOut* output,
1368                                             audio_io_handle_t id,
1369                                             uint32_t device,
1370                                             type_t type)
1371    :   ThreadBase(audioFlinger, id, device, type),
1372        mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1373        // Assumes constructor is called by AudioFlinger with it's mLock held,
1374        // but it would be safer to explicitly pass initial masterMute as parameter
1375        mMasterMute(audioFlinger->masterMute_l()),
1376        // mStreamTypes[] initialized in constructor body
1377        mOutput(output),
1378        // Assumes constructor is called by AudioFlinger with it's mLock held,
1379        // but it would be safer to explicitly pass initial masterVolume as parameter
1380        mMasterVolume(audioFlinger->masterVolume_l()),
1381        mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
1382{
1383    snprintf(mName, kNameLength, "AudioOut_%d", id);
1384
1385    readOutputParameters();
1386
1387    // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
1388    // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1389    for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1390            stream = (audio_stream_type_t) (stream + 1)) {
1391        mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1392        mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
1393        // initialized by stream_type_t default constructor
1394        // mStreamTypes[stream].valid = true;
1395    }
1396}
1397
1398AudioFlinger::PlaybackThread::~PlaybackThread()
1399{
1400    delete [] mMixBuffer;
1401}
1402
1403status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1404{
1405    dumpInternals(fd, args);
1406    dumpTracks(fd, args);
1407    dumpEffectChains(fd, args);
1408    return NO_ERROR;
1409}
1410
1411status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1412{
1413    const size_t SIZE = 256;
1414    char buffer[SIZE];
1415    String8 result;
1416
1417    snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1418    result.append(buffer);
1419    result.append("   Name  Clien Typ Fmt Chn mask   Session Buf  S M F SRate LeftV RighV  Serv       User       Main buf   Aux Buf\n");
1420    for (size_t i = 0; i < mTracks.size(); ++i) {
1421        sp<Track> track = mTracks[i];
1422        if (track != 0) {
1423            track->dump(buffer, SIZE);
1424            result.append(buffer);
1425        }
1426    }
1427
1428    snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1429    result.append(buffer);
1430    result.append("   Name  Clien Typ Fmt Chn mask   Session Buf  S M F SRate LeftV RighV  Serv       User       Main buf   Aux Buf\n");
1431    for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1432        sp<Track> track = mActiveTracks[i].promote();
1433        if (track != 0) {
1434            track->dump(buffer, SIZE);
1435            result.append(buffer);
1436        }
1437    }
1438    write(fd, result.string(), result.size());
1439    return NO_ERROR;
1440}
1441
1442status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1443{
1444    const size_t SIZE = 256;
1445    char buffer[SIZE];
1446    String8 result;
1447
1448    snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1449    result.append(buffer);
1450    snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1451    result.append(buffer);
1452    snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1453    result.append(buffer);
1454    snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1455    result.append(buffer);
1456    snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1457    result.append(buffer);
1458    snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1459    result.append(buffer);
1460    snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1461    result.append(buffer);
1462    write(fd, result.string(), result.size());
1463
1464    dumpBase(fd, args);
1465
1466    return NO_ERROR;
1467}
1468
1469// Thread virtuals
1470status_t AudioFlinger::PlaybackThread::readyToRun()
1471{
1472    status_t status = initCheck();
1473    if (status == NO_ERROR) {
1474        ALOGI("AudioFlinger's thread %p ready to run", this);
1475    } else {
1476        ALOGE("No working audio driver found.");
1477    }
1478    return status;
1479}
1480
1481void AudioFlinger::PlaybackThread::onFirstRef()
1482{
1483    run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
1484}
1485
1486// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1487sp<AudioFlinger::PlaybackThread::Track>  AudioFlinger::PlaybackThread::createTrack_l(
1488        const sp<AudioFlinger::Client>& client,
1489        audio_stream_type_t streamType,
1490        uint32_t sampleRate,
1491        audio_format_t format,
1492        uint32_t channelMask,
1493        int frameCount,
1494        const sp<IMemory>& sharedBuffer,
1495        int sessionId,
1496        status_t *status)
1497{
1498    sp<Track> track;
1499    status_t lStatus;
1500
1501    if (mType == DIRECT) {
1502        if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1503            if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1504                ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1505                        "for output %p with format %d",
1506                        sampleRate, format, channelMask, mOutput, mFormat);
1507                lStatus = BAD_VALUE;
1508                goto Exit;
1509            }
1510        }
1511    } else {
1512        // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1513        if (sampleRate > mSampleRate*2) {
1514            ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1515            lStatus = BAD_VALUE;
1516            goto Exit;
1517        }
1518    }
1519
1520    lStatus = initCheck();
1521    if (lStatus != NO_ERROR) {
1522        ALOGE("Audio driver not initialized.");
1523        goto Exit;
1524    }
1525
1526    { // scope for mLock
1527        Mutex::Autolock _l(mLock);
1528
1529        // all tracks in same audio session must share the same routing strategy otherwise
1530        // conflicts will happen when tracks are moved from one output to another by audio policy
1531        // manager
1532        uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1533        for (size_t i = 0; i < mTracks.size(); ++i) {
1534            sp<Track> t = mTracks[i];
1535            if (t != 0) {
1536                uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1537                if (sessionId == t->sessionId() && strategy != actual) {
1538                    ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1539                            strategy, actual);
1540                    lStatus = BAD_VALUE;
1541                    goto Exit;
1542                }
1543            }
1544        }
1545
1546        track = new Track(this, client, streamType, sampleRate, format,
1547                channelMask, frameCount, sharedBuffer, sessionId);
1548        if (track->getCblk() == NULL || track->name() < 0) {
1549            lStatus = NO_MEMORY;
1550            goto Exit;
1551        }
1552        mTracks.add(track);
1553
1554        sp<EffectChain> chain = getEffectChain_l(sessionId);
1555        if (chain != 0) {
1556            ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1557            track->setMainBuffer(chain->inBuffer());
1558            chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
1559            chain->incTrackCnt();
1560        }
1561
1562        // invalidate track immediately if the stream type was moved to another thread since
1563        // createTrack() was called by the client process.
1564        if (!mStreamTypes[streamType].valid) {
1565            ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1566                 this, streamType);
1567            android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1568        }
1569    }
1570    lStatus = NO_ERROR;
1571
1572Exit:
1573    if(status) {
1574        *status = lStatus;
1575    }
1576    return track;
1577}
1578
1579uint32_t AudioFlinger::PlaybackThread::latency() const
1580{
1581    Mutex::Autolock _l(mLock);
1582    if (initCheck() == NO_ERROR) {
1583        return mOutput->stream->get_latency(mOutput->stream);
1584    } else {
1585        return 0;
1586    }
1587}
1588
1589status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1590{
1591    mMasterVolume = value;
1592    return NO_ERROR;
1593}
1594
1595status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1596{
1597    mMasterMute = muted;
1598    return NO_ERROR;
1599}
1600
1601status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
1602{
1603    mStreamTypes[stream].volume = value;
1604    return NO_ERROR;
1605}
1606
1607status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
1608{
1609    mStreamTypes[stream].mute = muted;
1610    return NO_ERROR;
1611}
1612
1613float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
1614{
1615    return mStreamTypes[stream].volume;
1616}
1617
1618bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
1619{
1620    return mStreamTypes[stream].mute;
1621}
1622
1623// addTrack_l() must be called with ThreadBase::mLock held
1624status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1625{
1626    status_t status = ALREADY_EXISTS;
1627
1628    // set retry count for buffer fill
1629    track->mRetryCount = kMaxTrackStartupRetries;
1630    if (mActiveTracks.indexOf(track) < 0) {
1631        // the track is newly added, make sure it fills up all its
1632        // buffers before playing. This is to ensure the client will
1633        // effectively get the latency it requested.
1634        track->mFillingUpStatus = Track::FS_FILLING;
1635        track->mResetDone = false;
1636        mActiveTracks.add(track);
1637        if (track->mainBuffer() != mMixBuffer) {
1638            sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1639            if (chain != 0) {
1640                ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1641                chain->incActiveTrackCnt();
1642            }
1643        }
1644
1645        status = NO_ERROR;
1646    }
1647
1648    ALOGV("mWaitWorkCV.broadcast");
1649    mWaitWorkCV.broadcast();
1650
1651    return status;
1652}
1653
1654// destroyTrack_l() must be called with ThreadBase::mLock held
1655void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1656{
1657    track->mState = TrackBase::TERMINATED;
1658    if (mActiveTracks.indexOf(track) < 0) {
1659        removeTrack_l(track);
1660    }
1661}
1662
1663void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1664{
1665    mTracks.remove(track);
1666    deleteTrackName_l(track->name());
1667    sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1668    if (chain != 0) {
1669        chain->decTrackCnt();
1670    }
1671}
1672
1673String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1674{
1675    String8 out_s8 = String8("");
1676    char *s;
1677
1678    Mutex::Autolock _l(mLock);
1679    if (initCheck() != NO_ERROR) {
1680        return out_s8;
1681    }
1682
1683    s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
1684    out_s8 = String8(s);
1685    free(s);
1686    return out_s8;
1687}
1688
1689// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1690void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1691    AudioSystem::OutputDescriptor desc;
1692    void *param2 = NULL;
1693
1694    ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1695
1696    switch (event) {
1697    case AudioSystem::OUTPUT_OPENED:
1698    case AudioSystem::OUTPUT_CONFIG_CHANGED:
1699        desc.channels = mChannelMask;
1700        desc.samplingRate = mSampleRate;
1701        desc.format = mFormat;
1702        desc.frameCount = mFrameCount;
1703        desc.latency = latency();
1704        param2 = &desc;
1705        break;
1706
1707    case AudioSystem::STREAM_CONFIG_CHANGED:
1708        param2 = &param;
1709    case AudioSystem::OUTPUT_CLOSED:
1710    default:
1711        break;
1712    }
1713    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1714}
1715
1716void AudioFlinger::PlaybackThread::readOutputParameters()
1717{
1718    mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1719    mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1720    mChannelCount = (uint16_t)popcount(mChannelMask);
1721    mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1722    mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
1723    mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
1724
1725    // FIXME - Current mixer implementation only supports stereo output: Always
1726    // Allocate a stereo buffer even if HW output is mono.
1727    delete[] mMixBuffer;
1728    mMixBuffer = new int16_t[mFrameCount * 2];
1729    memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1730
1731    // force reconfiguration of effect chains and engines to take new buffer size and audio
1732    // parameters into account
1733    // Note that mLock is not held when readOutputParameters() is called from the constructor
1734    // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1735    // matter.
1736    // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1737    Vector< sp<EffectChain> > effectChains = mEffectChains;
1738    for (size_t i = 0; i < effectChains.size(); i ++) {
1739        mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
1740    }
1741}
1742
1743status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1744{
1745    if (halFrames == NULL || dspFrames == NULL) {
1746        return BAD_VALUE;
1747    }
1748    Mutex::Autolock _l(mLock);
1749    if (initCheck() != NO_ERROR) {
1750        return INVALID_OPERATION;
1751    }
1752    *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
1753
1754    return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
1755}
1756
1757uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
1758{
1759    Mutex::Autolock _l(mLock);
1760    uint32_t result = 0;
1761    if (getEffectChain_l(sessionId) != 0) {
1762        result = EFFECT_SESSION;
1763    }
1764
1765    for (size_t i = 0; i < mTracks.size(); ++i) {
1766        sp<Track> track = mTracks[i];
1767        if (sessionId == track->sessionId() &&
1768                !(track->mCblk->flags & CBLK_INVALID_MSK)) {
1769            result |= TRACK_SESSION;
1770            break;
1771        }
1772    }
1773
1774    return result;
1775}
1776
1777uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1778{
1779    // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
1780    // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
1781    if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1782        return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1783    }
1784    for (size_t i = 0; i < mTracks.size(); i++) {
1785        sp<Track> track = mTracks[i];
1786        if (sessionId == track->sessionId() &&
1787                !(track->mCblk->flags & CBLK_INVALID_MSK)) {
1788            return AudioSystem::getStrategyForStream(track->streamType());
1789        }
1790    }
1791    return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
1792}
1793
1794
1795AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
1796{
1797    Mutex::Autolock _l(mLock);
1798    return mOutput;
1799}
1800
1801AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1802{
1803    Mutex::Autolock _l(mLock);
1804    AudioStreamOut *output = mOutput;
1805    mOutput = NULL;
1806    return output;
1807}
1808
1809// this method must always be called either with ThreadBase mLock held or inside the thread loop
1810audio_stream_t* AudioFlinger::PlaybackThread::stream()
1811{
1812    if (mOutput == NULL) {
1813        return NULL;
1814    }
1815    return &mOutput->stream->common;
1816}
1817
1818uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1819{
1820    // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1821    // decoding and transfer time. So sleeping for half of the latency would likely cause
1822    // underruns
1823    if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1824        return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1825    } else {
1826        return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1827    }
1828}
1829
1830// ----------------------------------------------------------------------------
1831
1832AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1833        audio_io_handle_t id, uint32_t device, type_t type)
1834    :   PlaybackThread(audioFlinger, output, id, device, type),
1835        mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1836        mPrevMixerStatus(MIXER_IDLE)
1837{
1838    // FIXME - Current mixer implementation only supports stereo output
1839    if (mChannelCount == 1) {
1840        ALOGE("Invalid audio hardware channel count");
1841    }
1842}
1843
1844AudioFlinger::MixerThread::~MixerThread()
1845{
1846    delete mAudioMixer;
1847}
1848
1849bool AudioFlinger::MixerThread::threadLoop()
1850{
1851    Vector< sp<Track> > tracksToRemove;
1852    mixer_state mixerStatus = MIXER_IDLE;
1853    nsecs_t standbyTime = systemTime();
1854    size_t mixBufferSize = mFrameCount * mFrameSize;
1855    // FIXME: Relaxed timing because of a certain device that can't meet latency
1856    // Should be reduced to 2x after the vendor fixes the driver issue
1857    // increase threshold again due to low power audio mode. The way this warning threshold is
1858    // calculated and its usefulness should be reconsidered anyway.
1859    nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
1860    nsecs_t lastWarning = 0;
1861    bool longStandbyExit = false;
1862    uint32_t activeSleepTime = activeSleepTimeUs();
1863    uint32_t idleSleepTime = idleSleepTimeUs();
1864    uint32_t sleepTime = idleSleepTime;
1865    uint32_t sleepTimeShift = 0;
1866    Vector< sp<EffectChain> > effectChains;
1867#ifdef DEBUG_CPU_USAGE
1868    ThreadCpuUsage cpu;
1869    const CentralTendencyStatistics& stats = cpu.statistics();
1870#endif
1871
1872    acquireWakeLock();
1873
1874    while (!exitPending())
1875    {
1876#ifdef DEBUG_CPU_USAGE
1877        cpu.sampleAndEnable();
1878        unsigned n = stats.n();
1879        // cpu.elapsed() is expensive, so don't call it every loop
1880        if ((n & 127) == 1) {
1881            long long elapsed = cpu.elapsed();
1882            if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1883                double perLoop = elapsed / (double) n;
1884                double perLoop100 = perLoop * 0.01;
1885                double mean = stats.mean();
1886                double stddev = stats.stddev();
1887                double minimum = stats.minimum();
1888                double maximum = stats.maximum();
1889                cpu.resetStatistics();
1890                ALOGI("CPU usage over past %.1f secs (%u mixer loops at %.1f mean ms per loop):\n  us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n  %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f",
1891                        elapsed * .000000001, n, perLoop * .000001,
1892                        mean * .001,
1893                        stddev * .001,
1894                        minimum * .001,
1895                        maximum * .001,
1896                        mean / perLoop100,
1897                        stddev / perLoop100,
1898                        minimum / perLoop100,
1899                        maximum / perLoop100);
1900            }
1901        }
1902#endif
1903        processConfigEvents();
1904
1905        mixerStatus = MIXER_IDLE;
1906        { // scope for mLock
1907
1908            Mutex::Autolock _l(mLock);
1909
1910            if (checkForNewParameters_l()) {
1911                mixBufferSize = mFrameCount * mFrameSize;
1912                // FIXME: Relaxed timing because of a certain device that can't meet latency
1913                // Should be reduced to 2x after the vendor fixes the driver issue
1914                // increase threshold again due to low power audio mode. The way this warning
1915                // threshold is calculated and its usefulness should be reconsidered anyway.
1916                maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
1917                activeSleepTime = activeSleepTimeUs();
1918                idleSleepTime = idleSleepTimeUs();
1919            }
1920
1921            const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1922
1923            // put audio hardware into standby after short delay
1924            if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1925                        mSuspended)) {
1926                if (!mStandby) {
1927                    ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d", this, mSuspended);
1928                    mOutput->stream->common.standby(&mOutput->stream->common);
1929                    mStandby = true;
1930                    mBytesWritten = 0;
1931                }
1932
1933                if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1934                    // we're about to wait, flush the binder command buffer
1935                    IPCThreadState::self()->flushCommands();
1936
1937                    if (exitPending()) break;
1938
1939                    releaseWakeLock_l();
1940                    // wait until we have something to do...
1941                    ALOGV("MixerThread %p TID %d going to sleep", this, gettid());
1942                    mWaitWorkCV.wait(mLock);
1943                    ALOGV("MixerThread %p TID %d waking up", this, gettid());
1944                    acquireWakeLock_l();
1945
1946                    mPrevMixerStatus = MIXER_IDLE;
1947                    if (!mMasterMute) {
1948                        char value[PROPERTY_VALUE_MAX];
1949                        property_get("ro.audio.silent", value, "0");
1950                        if (atoi(value)) {
1951                            ALOGD("Silence is golden");
1952                            setMasterMute(true);
1953                        }
1954                    }
1955
1956                    standbyTime = systemTime() + kStandbyTimeInNsecs;
1957                    sleepTime = idleSleepTime;
1958                    sleepTimeShift = 0;
1959                    continue;
1960                }
1961            }
1962
1963            mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1964
1965            // prevent any changes in effect chain list and in each effect chain
1966            // during mixing and effect process as the audio buffers could be deleted
1967            // or modified if an effect is created or deleted
1968            lockEffectChains_l(effectChains);
1969        }
1970
1971        if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1972            // mix buffers...
1973            mAudioMixer->process();
1974            // increase sleep time progressively when application underrun condition clears.
1975            // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1976            // that a steady state of alternating ready/not ready conditions keeps the sleep time
1977            // such that we would underrun the audio HAL.
1978            if ((sleepTime == 0) && (sleepTimeShift > 0)) {
1979                sleepTimeShift--;
1980            }
1981            sleepTime = 0;
1982            standbyTime = systemTime() + kStandbyTimeInNsecs;
1983            //TODO: delay standby when effects have a tail
1984        } else {
1985            // If no tracks are ready, sleep once for the duration of an output
1986            // buffer size, then write 0s to the output
1987            if (sleepTime == 0) {
1988                if (mixerStatus == MIXER_TRACKS_ENABLED) {
1989                    sleepTime = activeSleepTime >> sleepTimeShift;
1990                    if (sleepTime < kMinThreadSleepTimeUs) {
1991                        sleepTime = kMinThreadSleepTimeUs;
1992                    }
1993                    // reduce sleep time in case of consecutive application underruns to avoid
1994                    // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1995                    // duration we would end up writing less data than needed by the audio HAL if
1996                    // the condition persists.
1997                    if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1998                        sleepTimeShift++;
1999                    }
2000                } else {
2001                    sleepTime = idleSleepTime;
2002                }
2003            } else if (mBytesWritten != 0 ||
2004                       (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2005                memset (mMixBuffer, 0, mixBufferSize);
2006                sleepTime = 0;
2007                ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
2008            }
2009            // TODO add standby time extension fct of effect tail
2010        }
2011
2012        if (mSuspended) {
2013            sleepTime = suspendSleepTimeUs();
2014        }
2015        // sleepTime == 0 means we must write to audio hardware
2016        if (sleepTime == 0) {
2017            for (size_t i = 0; i < effectChains.size(); i ++) {
2018                effectChains[i]->process_l();
2019            }
2020            // enable changes in effect chain
2021            unlockEffectChains(effectChains);
2022            mLastWriteTime = systemTime();
2023            mInWrite = true;
2024            mBytesWritten += mixBufferSize;
2025
2026            int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2027            if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2028            mNumWrites++;
2029            mInWrite = false;
2030            nsecs_t now = systemTime();
2031            nsecs_t delta = now - mLastWriteTime;
2032            if (!mStandby && delta > maxPeriod) {
2033                mNumDelayedWrites++;
2034                if ((now - lastWarning) > kWarningThrottleNs) {
2035                    ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2036                            ns2ms(delta), mNumDelayedWrites, this);
2037                    lastWarning = now;
2038                }
2039                if (mStandby) {
2040                    longStandbyExit = true;
2041                }
2042            }
2043            mStandby = false;
2044        } else {
2045            // enable changes in effect chain
2046            unlockEffectChains(effectChains);
2047            usleep(sleepTime);
2048        }
2049
2050        // finally let go of all our tracks, without the lock held
2051        // since we can't guarantee the destructors won't acquire that
2052        // same lock.
2053        tracksToRemove.clear();
2054
2055        // Effect chains will be actually deleted here if they were removed from
2056        // mEffectChains list during mixing or effects processing
2057        effectChains.clear();
2058    }
2059
2060    if (!mStandby) {
2061        mOutput->stream->common.standby(&mOutput->stream->common);
2062    }
2063
2064    releaseWakeLock();
2065
2066    ALOGV("MixerThread %p exiting", this);
2067    return false;
2068}
2069
2070// prepareTracks_l() must be called with ThreadBase::mLock held
2071AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2072        const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2073{
2074
2075    mixer_state mixerStatus = MIXER_IDLE;
2076    // find out which tracks need to be processed
2077    size_t count = activeTracks.size();
2078    size_t mixedTracks = 0;
2079    size_t tracksWithEffect = 0;
2080
2081    float masterVolume = mMasterVolume;
2082    bool  masterMute = mMasterMute;
2083
2084    if (masterMute) {
2085        masterVolume = 0;
2086    }
2087    // Delegate master volume control to effect in output mix effect chain if needed
2088    sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
2089    if (chain != 0) {
2090        uint32_t v = (uint32_t)(masterVolume * (1 << 24));
2091        chain->setVolume_l(&v, &v);
2092        masterVolume = (float)((v + (1 << 23)) >> 24);
2093        chain.clear();
2094    }
2095
2096    for (size_t i=0 ; i<count ; i++) {
2097        sp<Track> t = activeTracks[i].promote();
2098        if (t == 0) continue;
2099
2100        // this const just means the local variable doesn't change
2101        Track* const track = t.get();
2102        audio_track_cblk_t* cblk = track->cblk();
2103
2104        // The first time a track is added we wait
2105        // for all its buffers to be filled before processing it
2106        int name = track->name();
2107        // make sure that we have enough frames to mix one full buffer.
2108        // enforce this condition only once to enable draining the buffer in case the client
2109        // app does not call stop() and relies on underrun to stop:
2110        // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
2111        // during last round
2112        uint32_t minFrames = 1;
2113        if (!track->isStopped() && !track->isPausing() &&
2114                (mPrevMixerStatus == MIXER_TRACKS_READY)) {
2115            if (t->sampleRate() == (int)mSampleRate) {
2116                minFrames = mFrameCount;
2117            } else {
2118                // +1 for rounding and +1 for additional sample needed for interpolation
2119                minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2120                // add frames already consumed but not yet released by the resampler
2121                // because cblk->framesReady() will  include these frames
2122                minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2123                // the minimum track buffer size is normally twice the number of frames necessary
2124                // to fill one buffer and the resampler should not leave more than one buffer worth
2125                // of unreleased frames after each pass, but just in case...
2126                ALOG_ASSERT(minFrames <= cblk->frameCount);
2127            }
2128        }
2129        if ((cblk->framesReady() >= minFrames) && track->isReady() &&
2130                !track->isPaused() && !track->isTerminated())
2131        {
2132            //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
2133
2134            mixedTracks++;
2135
2136            // track->mainBuffer() != mMixBuffer means there is an effect chain
2137            // connected to the track
2138            chain.clear();
2139            if (track->mainBuffer() != mMixBuffer) {
2140                chain = getEffectChain_l(track->sessionId());
2141                // Delegate volume control to effect in track effect chain if needed
2142                if (chain != 0) {
2143                    tracksWithEffect++;
2144                } else {
2145                    ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
2146                            name, track->sessionId());
2147                }
2148            }
2149
2150
2151            int param = AudioMixer::VOLUME;
2152            if (track->mFillingUpStatus == Track::FS_FILLED) {
2153                // no ramp for the first volume setting
2154                track->mFillingUpStatus = Track::FS_ACTIVE;
2155                if (track->mState == TrackBase::RESUMING) {
2156                    track->mState = TrackBase::ACTIVE;
2157                    param = AudioMixer::RAMP_VOLUME;
2158                }
2159                mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
2160            } else if (cblk->server != 0) {
2161                // If the track is stopped before the first frame was mixed,
2162                // do not apply ramp
2163                param = AudioMixer::RAMP_VOLUME;
2164            }
2165
2166            // compute volume for this track
2167            uint32_t vl, vr, va;
2168            if (track->isMuted() || track->isPausing() ||
2169                mStreamTypes[track->streamType()].mute) {
2170                vl = vr = va = 0;
2171                if (track->isPausing()) {
2172                    track->setPaused();
2173                }
2174            } else {
2175
2176                // read original volumes with volume control
2177                float typeVolume = mStreamTypes[track->streamType()].volume;
2178                float v = masterVolume * typeVolume;
2179                uint32_t vlr = cblk->getVolumeLR();
2180                vl = vlr & 0xFFFF;
2181                vr = vlr >> 16;
2182                // track volumes come from shared memory, so can't be trusted and must be clamped
2183                if (vl > MAX_GAIN_INT) {
2184                    ALOGV("Track left volume out of range: %04X", vl);
2185                    vl = MAX_GAIN_INT;
2186                }
2187                if (vr > MAX_GAIN_INT) {
2188                    ALOGV("Track right volume out of range: %04X", vr);
2189                    vr = MAX_GAIN_INT;
2190                }
2191                // now apply the master volume and stream type volume
2192                vl = (uint32_t)(v * vl) << 12;
2193                vr = (uint32_t)(v * vr) << 12;
2194                // assuming master volume and stream type volume each go up to 1.0,
2195                // vl and vr are now in 8.24 format
2196
2197                uint16_t sendLevel = cblk->getSendLevel_U4_12();
2198                // send level comes from shared memory and so may be corrupt
2199                if (sendLevel >= MAX_GAIN_INT) {
2200                    ALOGV("Track send level out of range: %04X", sendLevel);
2201                    sendLevel = MAX_GAIN_INT;
2202                }
2203                va = (uint32_t)(v * sendLevel);
2204            }
2205            // Delegate volume control to effect in track effect chain if needed
2206            if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2207                // Do not ramp volume if volume is controlled by effect
2208                param = AudioMixer::VOLUME;
2209                track->mHasVolumeController = true;
2210            } else {
2211                // force no volume ramp when volume controller was just disabled or removed
2212                // from effect chain to avoid volume spike
2213                if (track->mHasVolumeController) {
2214                    param = AudioMixer::VOLUME;
2215                }
2216                track->mHasVolumeController = false;
2217            }
2218
2219            // Convert volumes from 8.24 to 4.12 format
2220            int16_t left, right, aux;
2221            // This additional clamping is needed in case chain->setVolume_l() overshot
2222            uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2223            if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2224            left = int16_t(v_clamped);
2225            v_clamped = (vr + (1 << 11)) >> 12;
2226            if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2227            right = int16_t(v_clamped);
2228
2229            if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2230            aux = int16_t(va);
2231
2232            // XXX: these things DON'T need to be done each time
2233            mAudioMixer->setBufferProvider(name, track);
2234            mAudioMixer->enable(name);
2235
2236            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2237            mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2238            mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
2239            mAudioMixer->setParameter(
2240                name,
2241                AudioMixer::TRACK,
2242                AudioMixer::FORMAT, (void *)track->format());
2243            mAudioMixer->setParameter(
2244                name,
2245                AudioMixer::TRACK,
2246                AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
2247            mAudioMixer->setParameter(
2248                name,
2249                AudioMixer::RESAMPLE,
2250                AudioMixer::SAMPLE_RATE,
2251                (void *)(cblk->sampleRate));
2252            mAudioMixer->setParameter(
2253                name,
2254                AudioMixer::TRACK,
2255                AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2256            mAudioMixer->setParameter(
2257                name,
2258                AudioMixer::TRACK,
2259                AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2260
2261            // reset retry count
2262            track->mRetryCount = kMaxTrackRetries;
2263            // If one track is ready, set the mixer ready if:
2264            //  - the mixer was not ready during previous round OR
2265            //  - no other track is not ready
2266            if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2267                    mixerStatus != MIXER_TRACKS_ENABLED) {
2268                mixerStatus = MIXER_TRACKS_READY;
2269            }
2270        } else {
2271            //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
2272            if (track->isStopped()) {
2273                track->reset();
2274            }
2275            if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2276                // We have consumed all the buffers of this track.
2277                // Remove it from the list of active tracks.
2278                tracksToRemove->add(track);
2279            } else {
2280                // No buffers for this track. Give it a few chances to
2281                // fill a buffer, then remove it from active list.
2282                if (--(track->mRetryCount) <= 0) {
2283                    ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
2284                    tracksToRemove->add(track);
2285                    // indicate to client process that the track was disabled because of underrun
2286                    android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
2287                // If one track is not ready, mark the mixer also not ready if:
2288                //  - the mixer was ready during previous round OR
2289                //  - no other track is ready
2290                } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2291                                mixerStatus != MIXER_TRACKS_READY) {
2292                    mixerStatus = MIXER_TRACKS_ENABLED;
2293                }
2294            }
2295            mAudioMixer->disable(name);
2296        }
2297    }
2298
2299    // remove all the tracks that need to be...
2300    count = tracksToRemove->size();
2301    if (CC_UNLIKELY(count)) {
2302        for (size_t i=0 ; i<count ; i++) {
2303            const sp<Track>& track = tracksToRemove->itemAt(i);
2304            mActiveTracks.remove(track);
2305            if (track->mainBuffer() != mMixBuffer) {
2306                chain = getEffectChain_l(track->sessionId());
2307                if (chain != 0) {
2308                    ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
2309                    chain->decActiveTrackCnt();
2310                }
2311            }
2312            if (track->isTerminated()) {
2313                removeTrack_l(track);
2314            }
2315        }
2316    }
2317
2318    // mix buffer must be cleared if all tracks are connected to an
2319    // effect chain as in this case the mixer will not write to
2320    // mix buffer and track effects will accumulate into it
2321    if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2322        memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2323    }
2324
2325    mPrevMixerStatus = mixerStatus;
2326    return mixerStatus;
2327}
2328
2329void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
2330{
2331    ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2332            this,  streamType, mTracks.size());
2333    Mutex::Autolock _l(mLock);
2334
2335    size_t size = mTracks.size();
2336    for (size_t i = 0; i < size; i++) {
2337        sp<Track> t = mTracks[i];
2338        if (t->streamType() == streamType) {
2339            android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
2340            t->mCblk->cv.signal();
2341        }
2342    }
2343}
2344
2345void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
2346{
2347    ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
2348            this,  streamType, valid);
2349    Mutex::Autolock _l(mLock);
2350
2351    mStreamTypes[streamType].valid = valid;
2352}
2353
2354// getTrackName_l() must be called with ThreadBase::mLock held
2355int AudioFlinger::MixerThread::getTrackName_l()
2356{
2357    return mAudioMixer->getTrackName();
2358}
2359
2360// deleteTrackName_l() must be called with ThreadBase::mLock held
2361void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2362{
2363    ALOGV("remove track (%d) and delete from mixer", name);
2364    mAudioMixer->deleteTrackName(name);
2365}
2366
2367// checkForNewParameters_l() must be called with ThreadBase::mLock held
2368bool AudioFlinger::MixerThread::checkForNewParameters_l()
2369{
2370    bool reconfig = false;
2371
2372    while (!mNewParameters.isEmpty()) {
2373        status_t status = NO_ERROR;
2374        String8 keyValuePair = mNewParameters[0];
2375        AudioParameter param = AudioParameter(keyValuePair);
2376        int value;
2377
2378        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2379            reconfig = true;
2380        }
2381        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
2382            if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
2383                status = BAD_VALUE;
2384            } else {
2385                reconfig = true;
2386            }
2387        }
2388        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
2389            if (value != AUDIO_CHANNEL_OUT_STEREO) {
2390                status = BAD_VALUE;
2391            } else {
2392                reconfig = true;
2393            }
2394        }
2395        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2396            // do not accept frame count changes if tracks are open as the track buffer
2397            // size depends on frame count and correct behavior would not be guaranteed
2398            // if frame count is changed after track creation
2399            if (!mTracks.isEmpty()) {
2400                status = INVALID_OPERATION;
2401            } else {
2402                reconfig = true;
2403            }
2404        }
2405        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
2406            // when changing the audio output device, call addBatteryData to notify
2407            // the change
2408            if ((int)mDevice != value) {
2409                uint32_t params = 0;
2410                // check whether speaker is on
2411                if (value & AUDIO_DEVICE_OUT_SPEAKER) {
2412                    params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2413                }
2414
2415                int deviceWithoutSpeaker
2416                    = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
2417                // check if any other device (except speaker) is on
2418                if (value & deviceWithoutSpeaker ) {
2419                    params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2420                }
2421
2422                if (params != 0) {
2423                    addBatteryData(params);
2424                }
2425            }
2426
2427            // forward device change to effects that have requested to be
2428            // aware of attached audio device.
2429            mDevice = (uint32_t)value;
2430            for (size_t i = 0; i < mEffectChains.size(); i++) {
2431                mEffectChains[i]->setDevice_l(mDevice);
2432            }
2433        }
2434
2435        if (status == NO_ERROR) {
2436            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
2437                                                    keyValuePair.string());
2438            if (!mStandby && status == INVALID_OPERATION) {
2439               mOutput->stream->common.standby(&mOutput->stream->common);
2440               mStandby = true;
2441               mBytesWritten = 0;
2442               status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
2443                                                       keyValuePair.string());
2444            }
2445            if (status == NO_ERROR && reconfig) {
2446                delete mAudioMixer;
2447                // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2448                mAudioMixer = NULL;
2449                readOutputParameters();
2450                mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2451                for (size_t i = 0; i < mTracks.size() ; i++) {
2452                    int name = getTrackName_l();
2453                    if (name < 0) break;
2454                    mTracks[i]->mName = name;
2455                    // limit track sample rate to 2 x new output sample rate
2456                    if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2457                        mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2458                    }
2459                }
2460                sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2461            }
2462        }
2463
2464        mNewParameters.removeAt(0);
2465
2466        mParamStatus = status;
2467        mParamCond.signal();
2468        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2469        // already timed out waiting for the status and will never signal the condition.
2470        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
2471    }
2472    return reconfig;
2473}
2474
2475status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2476{
2477    const size_t SIZE = 256;
2478    char buffer[SIZE];
2479    String8 result;
2480
2481    PlaybackThread::dumpInternals(fd, args);
2482
2483    snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2484    result.append(buffer);
2485    write(fd, result.string(), result.size());
2486    return NO_ERROR;
2487}
2488
2489uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2490{
2491    return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
2492}
2493
2494uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2495{
2496    return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2497}
2498
2499// ----------------------------------------------------------------------------
2500AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2501        AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
2502    :   PlaybackThread(audioFlinger, output, id, device, DIRECT)
2503        // mLeftVolFloat, mRightVolFloat
2504        // mLeftVolShort, mRightVolShort
2505{
2506}
2507
2508AudioFlinger::DirectOutputThread::~DirectOutputThread()
2509{
2510}
2511
2512void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2513{
2514    // Do not apply volume on compressed audio
2515    if (!audio_is_linear_pcm(mFormat)) {
2516        return;
2517    }
2518
2519    // convert to signed 16 bit before volume calculation
2520    if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2521        size_t count = mFrameCount * mChannelCount;
2522        uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2523        int16_t *dst = mMixBuffer + count-1;
2524        while(count--) {
2525            *dst-- = (int16_t)(*src--^0x80) << 8;
2526        }
2527    }
2528
2529    size_t frameCount = mFrameCount;
2530    int16_t *out = mMixBuffer;
2531    if (ramp) {
2532        if (mChannelCount == 1) {
2533            int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2534            int32_t vlInc = d / (int32_t)frameCount;
2535            int32_t vl = ((int32_t)mLeftVolShort << 16);
2536            do {
2537                out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2538                out++;
2539                vl += vlInc;
2540            } while (--frameCount);
2541
2542        } else {
2543            int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2544            int32_t vlInc = d / (int32_t)frameCount;
2545            d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2546            int32_t vrInc = d / (int32_t)frameCount;
2547            int32_t vl = ((int32_t)mLeftVolShort << 16);
2548            int32_t vr = ((int32_t)mRightVolShort << 16);
2549            do {
2550                out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2551                out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2552                out += 2;
2553                vl += vlInc;
2554                vr += vrInc;
2555            } while (--frameCount);
2556        }
2557    } else {
2558        if (mChannelCount == 1) {
2559            do {
2560                out[0] = clamp16(mul(out[0], leftVol) >> 12);
2561                out++;
2562            } while (--frameCount);
2563        } else {
2564            do {
2565                out[0] = clamp16(mul(out[0], leftVol) >> 12);
2566                out[1] = clamp16(mul(out[1], rightVol) >> 12);
2567                out += 2;
2568            } while (--frameCount);
2569        }
2570    }
2571
2572    // convert back to unsigned 8 bit after volume calculation
2573    if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
2574        size_t count = mFrameCount * mChannelCount;
2575        int16_t *src = mMixBuffer;
2576        uint8_t *dst = (uint8_t *)mMixBuffer;
2577        while(count--) {
2578            *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2579        }
2580    }
2581
2582    mLeftVolShort = leftVol;
2583    mRightVolShort = rightVol;
2584}
2585
2586bool AudioFlinger::DirectOutputThread::threadLoop()
2587{
2588    mixer_state mixerStatus = MIXER_IDLE;
2589    sp<Track> trackToRemove;
2590    sp<Track> activeTrack;
2591    nsecs_t standbyTime = systemTime();
2592    int8_t *curBuf;
2593    size_t mixBufferSize = mFrameCount*mFrameSize;
2594    uint32_t activeSleepTime = activeSleepTimeUs();
2595    uint32_t idleSleepTime = idleSleepTimeUs();
2596    uint32_t sleepTime = idleSleepTime;
2597    // use shorter standby delay as on normal output to release
2598    // hardware resources as soon as possible
2599    nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2600
2601    acquireWakeLock();
2602
2603    while (!exitPending())
2604    {
2605        bool rampVolume;
2606        uint16_t leftVol;
2607        uint16_t rightVol;
2608        Vector< sp<EffectChain> > effectChains;
2609
2610        processConfigEvents();
2611
2612        mixerStatus = MIXER_IDLE;
2613
2614        { // scope for the mLock
2615
2616            Mutex::Autolock _l(mLock);
2617
2618            if (checkForNewParameters_l()) {
2619                mixBufferSize = mFrameCount*mFrameSize;
2620                activeSleepTime = activeSleepTimeUs();
2621                idleSleepTime = idleSleepTimeUs();
2622                standbyDelay = microseconds(activeSleepTime*2);
2623            }
2624
2625            // put audio hardware into standby after short delay
2626            if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2627                        mSuspended)) {
2628                // wait until we have something to do...
2629                if (!mStandby) {
2630                    ALOGV("Audio hardware entering standby, mixer %p", this);
2631                    mOutput->stream->common.standby(&mOutput->stream->common);
2632                    mStandby = true;
2633                    mBytesWritten = 0;
2634                }
2635
2636                if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2637                    // we're about to wait, flush the binder command buffer
2638                    IPCThreadState::self()->flushCommands();
2639
2640                    if (exitPending()) break;
2641
2642                    releaseWakeLock_l();
2643                    ALOGV("DirectOutputThread %p TID %d going to sleep", this, gettid());
2644                    mWaitWorkCV.wait(mLock);
2645                    ALOGV("DirectOutputThread %p TID %d waking up in active mode", this, gettid());
2646                    acquireWakeLock_l();
2647
2648                    if (!mMasterMute) {
2649                        char value[PROPERTY_VALUE_MAX];
2650                        property_get("ro.audio.silent", value, "0");
2651                        if (atoi(value)) {
2652                            ALOGD("Silence is golden");
2653                            setMasterMute(true);
2654                        }
2655                    }
2656
2657                    standbyTime = systemTime() + standbyDelay;
2658                    sleepTime = idleSleepTime;
2659                    continue;
2660                }
2661            }
2662
2663            effectChains = mEffectChains;
2664
2665            // find out which tracks need to be processed
2666            if (mActiveTracks.size() != 0) {
2667                sp<Track> t = mActiveTracks[0].promote();
2668                if (t == 0) continue;
2669
2670                Track* const track = t.get();
2671                audio_track_cblk_t* cblk = track->cblk();
2672
2673                // The first time a track is added we wait
2674                // for all its buffers to be filled before processing it
2675                if (cblk->framesReady() && track->isReady() &&
2676                        !track->isPaused() && !track->isTerminated())
2677                {
2678                    //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2679
2680                    if (track->mFillingUpStatus == Track::FS_FILLED) {
2681                        track->mFillingUpStatus = Track::FS_ACTIVE;
2682                        mLeftVolFloat = mRightVolFloat = 0;
2683                        mLeftVolShort = mRightVolShort = 0;
2684                        if (track->mState == TrackBase::RESUMING) {
2685                            track->mState = TrackBase::ACTIVE;
2686                            rampVolume = true;
2687                        }
2688                    } else if (cblk->server != 0) {
2689                        // If the track is stopped before the first frame was mixed,
2690                        // do not apply ramp
2691                        rampVolume = true;
2692                    }
2693                    // compute volume for this track
2694                    float left, right;
2695                    if (track->isMuted() || mMasterMute || track->isPausing() ||
2696                        mStreamTypes[track->streamType()].mute) {
2697                        left = right = 0;
2698                        if (track->isPausing()) {
2699                            track->setPaused();
2700                        }
2701                    } else {
2702                        float typeVolume = mStreamTypes[track->streamType()].volume;
2703                        float v = mMasterVolume * typeVolume;
2704                        uint32_t vlr = cblk->getVolumeLR();
2705                        float v_clamped = v * (vlr & 0xFFFF);
2706                        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2707                        left = v_clamped/MAX_GAIN;
2708                        v_clamped = v * (vlr >> 16);
2709                        if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2710                        right = v_clamped/MAX_GAIN;
2711                    }
2712
2713                    if (left != mLeftVolFloat || right != mRightVolFloat) {
2714                        mLeftVolFloat = left;
2715                        mRightVolFloat = right;
2716
2717                        // If audio HAL implements volume control,
2718                        // force software volume to nominal value
2719                        if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
2720                            left = 1.0f;
2721                            right = 1.0f;
2722                        }
2723
2724                        // Convert volumes from float to 8.24
2725                        uint32_t vl = (uint32_t)(left * (1 << 24));
2726                        uint32_t vr = (uint32_t)(right * (1 << 24));
2727
2728                        // Delegate volume control to effect in track effect chain if needed
2729                        // only one effect chain can be present on DirectOutputThread, so if
2730                        // there is one, the track is connected to it
2731                        if (!effectChains.isEmpty()) {
2732                            // Do not ramp volume if volume is controlled by effect
2733                            if(effectChains[0]->setVolume_l(&vl, &vr)) {
2734                                rampVolume = false;
2735                            }
2736                        }
2737
2738                        // Convert volumes from 8.24 to 4.12 format
2739                        uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2740                        if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2741                        leftVol = (uint16_t)v_clamped;
2742                        v_clamped = (vr + (1 << 11)) >> 12;
2743                        if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2744                        rightVol = (uint16_t)v_clamped;
2745                    } else {
2746                        leftVol = mLeftVolShort;
2747                        rightVol = mRightVolShort;
2748                        rampVolume = false;
2749                    }
2750
2751                    // reset retry count
2752                    track->mRetryCount = kMaxTrackRetriesDirect;
2753                    activeTrack = t;
2754                    mixerStatus = MIXER_TRACKS_READY;
2755                } else {
2756                    //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2757                    if (track->isStopped()) {
2758                        track->reset();
2759                    }
2760                    if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2761                        // We have consumed all the buffers of this track.
2762                        // Remove it from the list of active tracks.
2763                        trackToRemove = track;
2764                    } else {
2765                        // No buffers for this track. Give it a few chances to
2766                        // fill a buffer, then remove it from active list.
2767                        if (--(track->mRetryCount) <= 0) {
2768                            ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2769                            trackToRemove = track;
2770                        } else {
2771                            mixerStatus = MIXER_TRACKS_ENABLED;
2772                        }
2773                    }
2774                }
2775            }
2776
2777            // remove all the tracks that need to be...
2778            if (CC_UNLIKELY(trackToRemove != 0)) {
2779                mActiveTracks.remove(trackToRemove);
2780                if (!effectChains.isEmpty()) {
2781                    ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2782                            trackToRemove->sessionId());
2783                    effectChains[0]->decActiveTrackCnt();
2784                }
2785                if (trackToRemove->isTerminated()) {
2786                    removeTrack_l(trackToRemove);
2787                }
2788            }
2789
2790            lockEffectChains_l(effectChains);
2791       }
2792
2793        if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2794            AudioBufferProvider::Buffer buffer;
2795            size_t frameCount = mFrameCount;
2796            curBuf = (int8_t *)mMixBuffer;
2797            // output audio to hardware
2798            while (frameCount) {
2799                buffer.frameCount = frameCount;
2800                activeTrack->getNextBuffer(&buffer);
2801                if (CC_UNLIKELY(buffer.raw == NULL)) {
2802                    memset(curBuf, 0, frameCount * mFrameSize);
2803                    break;
2804                }
2805                memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2806                frameCount -= buffer.frameCount;
2807                curBuf += buffer.frameCount * mFrameSize;
2808                activeTrack->releaseBuffer(&buffer);
2809            }
2810            sleepTime = 0;
2811            standbyTime = systemTime() + standbyDelay;
2812        } else {
2813            if (sleepTime == 0) {
2814                if (mixerStatus == MIXER_TRACKS_ENABLED) {
2815                    sleepTime = activeSleepTime;
2816                } else {
2817                    sleepTime = idleSleepTime;
2818                }
2819            } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
2820                memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2821                sleepTime = 0;
2822            }
2823        }
2824
2825        if (mSuspended) {
2826            sleepTime = suspendSleepTimeUs();
2827        }
2828        // sleepTime == 0 means we must write to audio hardware
2829        if (sleepTime == 0) {
2830            if (mixerStatus == MIXER_TRACKS_READY) {
2831                applyVolume(leftVol, rightVol, rampVolume);
2832            }
2833            for (size_t i = 0; i < effectChains.size(); i ++) {
2834                effectChains[i]->process_l();
2835            }
2836            unlockEffectChains(effectChains);
2837
2838            mLastWriteTime = systemTime();
2839            mInWrite = true;
2840            mBytesWritten += mixBufferSize;
2841            int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
2842            if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2843            mNumWrites++;
2844            mInWrite = false;
2845            mStandby = false;
2846        } else {
2847            unlockEffectChains(effectChains);
2848            usleep(sleepTime);
2849        }
2850
2851        // finally let go of removed track, without the lock held
2852        // since we can't guarantee the destructors won't acquire that
2853        // same lock.
2854        trackToRemove.clear();
2855        activeTrack.clear();
2856
2857        // Effect chains will be actually deleted here if they were removed from
2858        // mEffectChains list during mixing or effects processing
2859        effectChains.clear();
2860    }
2861
2862    if (!mStandby) {
2863        mOutput->stream->common.standby(&mOutput->stream->common);
2864    }
2865
2866    releaseWakeLock();
2867
2868    ALOGV("DirectOutputThread %p exiting", this);
2869    return false;
2870}
2871
2872// getTrackName_l() must be called with ThreadBase::mLock held
2873int AudioFlinger::DirectOutputThread::getTrackName_l()
2874{
2875    return 0;
2876}
2877
2878// deleteTrackName_l() must be called with ThreadBase::mLock held
2879void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2880{
2881}
2882
2883// checkForNewParameters_l() must be called with ThreadBase::mLock held
2884bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2885{
2886    bool reconfig = false;
2887
2888    while (!mNewParameters.isEmpty()) {
2889        status_t status = NO_ERROR;
2890        String8 keyValuePair = mNewParameters[0];
2891        AudioParameter param = AudioParameter(keyValuePair);
2892        int value;
2893
2894        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2895            // do not accept frame count changes if tracks are open as the track buffer
2896            // size depends on frame count and correct behavior would not be garantied
2897            // if frame count is changed after track creation
2898            if (!mTracks.isEmpty()) {
2899                status = INVALID_OPERATION;
2900            } else {
2901                reconfig = true;
2902            }
2903        }
2904        if (status == NO_ERROR) {
2905            status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
2906                                                    keyValuePair.string());
2907            if (!mStandby && status == INVALID_OPERATION) {
2908               mOutput->stream->common.standby(&mOutput->stream->common);
2909               mStandby = true;
2910               mBytesWritten = 0;
2911               status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
2912                                                       keyValuePair.string());
2913            }
2914            if (status == NO_ERROR && reconfig) {
2915                readOutputParameters();
2916                sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2917            }
2918        }
2919
2920        mNewParameters.removeAt(0);
2921
2922        mParamStatus = status;
2923        mParamCond.signal();
2924        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2925        // already timed out waiting for the status and will never signal the condition.
2926        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
2927    }
2928    return reconfig;
2929}
2930
2931uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2932{
2933    uint32_t time;
2934    if (audio_is_linear_pcm(mFormat)) {
2935        time = PlaybackThread::activeSleepTimeUs();
2936    } else {
2937        time = 10000;
2938    }
2939    return time;
2940}
2941
2942uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2943{
2944    uint32_t time;
2945    if (audio_is_linear_pcm(mFormat)) {
2946        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
2947    } else {
2948        time = 10000;
2949    }
2950    return time;
2951}
2952
2953uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2954{
2955    uint32_t time;
2956    if (audio_is_linear_pcm(mFormat)) {
2957        time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2958    } else {
2959        time = 10000;
2960    }
2961    return time;
2962}
2963
2964
2965// ----------------------------------------------------------------------------
2966
2967AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
2968        AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
2969    :   MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
2970        mWaitTimeMs(UINT_MAX)
2971{
2972    addOutputTrack(mainThread);
2973}
2974
2975AudioFlinger::DuplicatingThread::~DuplicatingThread()
2976{
2977    for (size_t i = 0; i < mOutputTracks.size(); i++) {
2978        mOutputTracks[i]->destroy();
2979    }
2980}
2981
2982bool AudioFlinger::DuplicatingThread::threadLoop()
2983{
2984    Vector< sp<Track> > tracksToRemove;
2985    mixer_state mixerStatus = MIXER_IDLE;
2986    nsecs_t standbyTime = systemTime();
2987    size_t mixBufferSize = mFrameCount*mFrameSize;
2988    SortedVector< sp<OutputTrack> > outputTracks;
2989    uint32_t writeFrames = 0;
2990    uint32_t activeSleepTime = activeSleepTimeUs();
2991    uint32_t idleSleepTime = idleSleepTimeUs();
2992    uint32_t sleepTime = idleSleepTime;
2993    Vector< sp<EffectChain> > effectChains;
2994
2995    acquireWakeLock();
2996
2997    while (!exitPending())
2998    {
2999        processConfigEvents();
3000
3001        mixerStatus = MIXER_IDLE;
3002        { // scope for the mLock
3003
3004            Mutex::Autolock _l(mLock);
3005
3006            if (checkForNewParameters_l()) {
3007                mixBufferSize = mFrameCount*mFrameSize;
3008                updateWaitTime();
3009                activeSleepTime = activeSleepTimeUs();
3010                idleSleepTime = idleSleepTimeUs();
3011            }
3012
3013            const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3014
3015            for (size_t i = 0; i < mOutputTracks.size(); i++) {
3016                outputTracks.add(mOutputTracks[i]);
3017            }
3018
3019            // put audio hardware into standby after short delay
3020            if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3021                         mSuspended)) {
3022                if (!mStandby) {
3023                    for (size_t i = 0; i < outputTracks.size(); i++) {
3024                        outputTracks[i]->stop();
3025                    }
3026                    mStandby = true;
3027                    mBytesWritten = 0;
3028                }
3029
3030                if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3031                    // we're about to wait, flush the binder command buffer
3032                    IPCThreadState::self()->flushCommands();
3033                    outputTracks.clear();
3034
3035                    if (exitPending()) break;
3036
3037                    releaseWakeLock_l();
3038                    ALOGV("DuplicatingThread %p TID %d going to sleep", this, gettid());
3039                    mWaitWorkCV.wait(mLock);
3040                    ALOGV("DuplicatingThread %p TID %d waking up", this, gettid());
3041                    acquireWakeLock_l();
3042
3043                    mPrevMixerStatus = MIXER_IDLE;
3044                    if (!mMasterMute) {
3045                        char value[PROPERTY_VALUE_MAX];
3046                        property_get("ro.audio.silent", value, "0");
3047                        if (atoi(value)) {
3048                            ALOGD("Silence is golden");
3049                            setMasterMute(true);
3050                        }
3051                    }
3052
3053                    standbyTime = systemTime() + kStandbyTimeInNsecs;
3054                    sleepTime = idleSleepTime;
3055                    continue;
3056                }
3057            }
3058
3059            mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3060
3061            // prevent any changes in effect chain list and in each effect chain
3062            // during mixing and effect process as the audio buffers could be deleted
3063            // or modified if an effect is created or deleted
3064            lockEffectChains_l(effectChains);
3065        }
3066
3067        if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
3068            // mix buffers...
3069            if (outputsReady(outputTracks)) {
3070                mAudioMixer->process();
3071            } else {
3072                memset(mMixBuffer, 0, mixBufferSize);
3073            }
3074            sleepTime = 0;
3075            writeFrames = mFrameCount;
3076        } else {
3077            if (sleepTime == 0) {
3078                if (mixerStatus == MIXER_TRACKS_ENABLED) {
3079                    sleepTime = activeSleepTime;
3080                } else {
3081                    sleepTime = idleSleepTime;
3082                }
3083            } else if (mBytesWritten != 0) {
3084                // flush remaining overflow buffers in output tracks
3085                for (size_t i = 0; i < outputTracks.size(); i++) {
3086                    if (outputTracks[i]->isActive()) {
3087                        sleepTime = 0;
3088                        writeFrames = 0;
3089                        memset(mMixBuffer, 0, mixBufferSize);
3090                        break;
3091                    }
3092                }
3093            }
3094        }
3095
3096        if (mSuspended) {
3097            sleepTime = suspendSleepTimeUs();
3098        }
3099        // sleepTime == 0 means we must write to audio hardware
3100        if (sleepTime == 0) {
3101            for (size_t i = 0; i < effectChains.size(); i ++) {
3102                effectChains[i]->process_l();
3103            }
3104            // enable changes in effect chain
3105            unlockEffectChains(effectChains);
3106
3107            standbyTime = systemTime() + kStandbyTimeInNsecs;
3108            for (size_t i = 0; i < outputTracks.size(); i++) {
3109                outputTracks[i]->write(mMixBuffer, writeFrames);
3110            }
3111            mStandby = false;
3112            mBytesWritten += mixBufferSize;
3113        } else {
3114            // enable changes in effect chain
3115            unlockEffectChains(effectChains);
3116            usleep(sleepTime);
3117        }
3118
3119        // finally let go of all our tracks, without the lock held
3120        // since we can't guarantee the destructors won't acquire that
3121        // same lock.
3122        tracksToRemove.clear();
3123        outputTracks.clear();
3124
3125        // Effect chains will be actually deleted here if they were removed from
3126        // mEffectChains list during mixing or effects processing
3127        effectChains.clear();
3128    }
3129
3130    releaseWakeLock();
3131
3132    return false;
3133}
3134
3135void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3136{
3137    int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3138    OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3139                                            this,
3140                                            mSampleRate,
3141                                            mFormat,
3142                                            mChannelMask,
3143                                            frameCount);
3144    if (outputTrack->cblk() != NULL) {
3145        thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
3146        mOutputTracks.add(outputTrack);
3147        ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
3148        updateWaitTime();
3149    }
3150}
3151
3152void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3153{
3154    Mutex::Autolock _l(mLock);
3155    for (size_t i = 0; i < mOutputTracks.size(); i++) {
3156        if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3157            mOutputTracks[i]->destroy();
3158            mOutputTracks.removeAt(i);
3159            updateWaitTime();
3160            return;
3161        }
3162    }
3163    ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
3164}
3165
3166void AudioFlinger::DuplicatingThread::updateWaitTime()
3167{
3168    mWaitTimeMs = UINT_MAX;
3169    for (size_t i = 0; i < mOutputTracks.size(); i++) {
3170        sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3171        if (strong != 0) {
3172            uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3173            if (waitTimeMs < mWaitTimeMs) {
3174                mWaitTimeMs = waitTimeMs;
3175            }
3176        }
3177    }
3178}
3179
3180
3181bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3182{
3183    for (size_t i = 0; i < outputTracks.size(); i++) {
3184        sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3185        if (thread == 0) {
3186            ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3187            return false;
3188        }
3189        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3190        if (playbackThread->standby() && !playbackThread->isSuspended()) {
3191            ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
3192            return false;
3193        }
3194    }
3195    return true;
3196}
3197
3198uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3199{
3200    return (mWaitTimeMs * 1000) / 2;
3201}
3202
3203// ----------------------------------------------------------------------------
3204
3205// TrackBase constructor must be called with AudioFlinger::mLock held
3206AudioFlinger::ThreadBase::TrackBase::TrackBase(
3207            const wp<ThreadBase>& thread,
3208            const sp<Client>& client,
3209            uint32_t sampleRate,
3210            audio_format_t format,
3211            uint32_t channelMask,
3212            int frameCount,
3213            uint32_t flags,
3214            const sp<IMemory>& sharedBuffer,
3215            int sessionId)
3216    :   RefBase(),
3217        mThread(thread),
3218        mClient(client),
3219        mCblk(NULL),
3220        // mBuffer
3221        // mBufferEnd
3222        mFrameCount(0),
3223        mState(IDLE),
3224        mFormat(format),
3225        mFlags(flags & ~SYSTEM_FLAGS_MASK),
3226        mSessionId(sessionId)
3227        // mChannelCount
3228        // mChannelMask
3229{
3230    ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3231
3232    // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3233   size_t size = sizeof(audio_track_cblk_t);
3234   uint8_t channelCount = popcount(channelMask);
3235   size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3236   if (sharedBuffer == 0) {
3237       size += bufferSize;
3238   }
3239
3240   if (client != NULL) {
3241        mCblkMemory = client->heap()->allocate(size);
3242        if (mCblkMemory != 0) {
3243            mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3244            if (mCblk != NULL) { // construct the shared structure in-place.
3245                new(mCblk) audio_track_cblk_t();
3246                // clear all buffers
3247                mCblk->frameCount = frameCount;
3248                mCblk->sampleRate = sampleRate;
3249                mChannelCount = channelCount;
3250                mChannelMask = channelMask;
3251                if (sharedBuffer == 0) {
3252                    mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3253                    memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3254                    // Force underrun condition to avoid false underrun callback until first data is
3255                    // written to buffer (other flags are cleared)
3256                    mCblk->flags = CBLK_UNDERRUN_ON;
3257                } else {
3258                    mBuffer = sharedBuffer->pointer();
3259                }
3260                mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3261            }
3262        } else {
3263            ALOGE("not enough memory for AudioTrack size=%u", size);
3264            client->heap()->dump("AudioTrack");
3265            return;
3266        }
3267   } else {
3268       mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3269           // construct the shared structure in-place.
3270           new(mCblk) audio_track_cblk_t();
3271           // clear all buffers
3272           mCblk->frameCount = frameCount;
3273           mCblk->sampleRate = sampleRate;
3274           mChannelCount = channelCount;
3275           mChannelMask = channelMask;
3276           mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3277           memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3278           // Force underrun condition to avoid false underrun callback until first data is
3279           // written to buffer (other flags are cleared)
3280           mCblk->flags = CBLK_UNDERRUN_ON;
3281           mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3282   }
3283}
3284
3285AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3286{
3287    if (mCblk != NULL) {
3288        if (mClient == 0) {
3289            delete mCblk;
3290        } else {
3291            mCblk->~audio_track_cblk_t();   // destroy our shared-structure.
3292        }
3293    }
3294    mCblkMemory.clear();    // free the shared memory before releasing the heap it belongs to
3295    if (mClient != 0) {
3296        // Client destructor must run with AudioFlinger mutex locked
3297        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3298        // If the client's reference count drops to zero, the associated destructor
3299        // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3300        // relying on the automatic clear() at end of scope.
3301        mClient.clear();
3302    }
3303}
3304
3305void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3306{
3307    buffer->raw = NULL;
3308    mFrameCount = buffer->frameCount;
3309    step();
3310    buffer->frameCount = 0;
3311}
3312
3313bool AudioFlinger::ThreadBase::TrackBase::step() {
3314    bool result;
3315    audio_track_cblk_t* cblk = this->cblk();
3316
3317    result = cblk->stepServer(mFrameCount);
3318    if (!result) {
3319        ALOGV("stepServer failed acquiring cblk mutex");
3320        mFlags |= STEPSERVER_FAILED;
3321    }
3322    return result;
3323}
3324
3325void AudioFlinger::ThreadBase::TrackBase::reset() {
3326    audio_track_cblk_t* cblk = this->cblk();
3327
3328    cblk->user = 0;
3329    cblk->server = 0;
3330    cblk->userBase = 0;
3331    cblk->serverBase = 0;
3332    mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
3333    ALOGV("TrackBase::reset");
3334}
3335
3336int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3337    return (int)mCblk->sampleRate;
3338}
3339
3340void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3341    audio_track_cblk_t* cblk = this->cblk();
3342    size_t frameSize = cblk->frameSize;
3343    int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3344    int8_t *bufferEnd = bufferStart + frames * frameSize;
3345
3346    // Check validity of returned pointer in case the track control block would have been corrupted.
3347    if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3348        ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
3349        ALOGE("TrackBase::getBuffer buffer out of range:\n    start: %p, end %p , mBuffer %p mBufferEnd %p\n    \
3350                server %d, serverBase %d, user %d, userBase %d",
3351                bufferStart, bufferEnd, mBuffer, mBufferEnd,
3352                cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
3353        return NULL;
3354    }
3355
3356    return bufferStart;
3357}
3358
3359// ----------------------------------------------------------------------------
3360
3361// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3362AudioFlinger::PlaybackThread::Track::Track(
3363            const wp<ThreadBase>& thread,
3364            const sp<Client>& client,
3365            audio_stream_type_t streamType,
3366            uint32_t sampleRate,
3367            audio_format_t format,
3368            uint32_t channelMask,
3369            int frameCount,
3370            const sp<IMemory>& sharedBuffer,
3371            int sessionId)
3372    :   TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
3373    mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3374    mAuxEffectId(0), mHasVolumeController(false)
3375{
3376    if (mCblk != NULL) {
3377        sp<ThreadBase> baseThread = thread.promote();
3378        if (baseThread != 0) {
3379            PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3380            mName = playbackThread->getTrackName_l();
3381            mMainBuffer = playbackThread->mixBuffer();
3382        }
3383        ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
3384        if (mName < 0) {
3385            ALOGE("no more track names available");
3386        }
3387        mStreamType = streamType;
3388        // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3389        // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
3390        mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
3391    }
3392}
3393
3394AudioFlinger::PlaybackThread::Track::~Track()
3395{
3396    ALOGV("PlaybackThread::Track destructor");
3397    sp<ThreadBase> thread = mThread.promote();
3398    if (thread != 0) {
3399        Mutex::Autolock _l(thread->mLock);
3400        mState = TERMINATED;
3401    }
3402}
3403
3404void AudioFlinger::PlaybackThread::Track::destroy()
3405{
3406    // NOTE: destroyTrack_l() can remove a strong reference to this Track
3407    // by removing it from mTracks vector, so there is a risk that this Tracks's
3408    // desctructor is called. As the destructor needs to lock mLock,
3409    // we must acquire a strong reference on this Track before locking mLock
3410    // here so that the destructor is called only when exiting this function.
3411    // On the other hand, as long as Track::destroy() is only called by
3412    // TrackHandle destructor, the TrackHandle still holds a strong ref on
3413    // this Track with its member mTrack.
3414    sp<Track> keep(this);
3415    { // scope for mLock
3416        sp<ThreadBase> thread = mThread.promote();
3417        if (thread != 0) {
3418            if (!isOutputTrack()) {
3419                if (mState == ACTIVE || mState == RESUMING) {
3420                    AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
3421
3422                    // to track the speaker usage
3423                    addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
3424                }
3425                AudioSystem::releaseOutput(thread->id());
3426            }
3427            Mutex::Autolock _l(thread->mLock);
3428            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3429            playbackThread->destroyTrack_l(this);
3430        }
3431    }
3432}
3433
3434void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3435{
3436    uint32_t vlr = mCblk->getVolumeLR();
3437    snprintf(buffer, size, "   %05d %05d %03u %03u 0x%08x %05u   %04u %1d %1d %1d %05u %05u %05u  0x%08x 0x%08x 0x%08x 0x%08x\n",
3438            mName - AudioMixer::TRACK0,
3439            (mClient == 0) ? getpid() : mClient->pid(),
3440            mStreamType,
3441            mFormat,
3442            mChannelMask,
3443            mSessionId,
3444            mFrameCount,
3445            mState,
3446            mMute,
3447            mFillingUpStatus,
3448            mCblk->sampleRate,
3449            vlr & 0xFFFF,
3450            vlr >> 16,
3451            mCblk->server,
3452            mCblk->user,
3453            (int)mMainBuffer,
3454            (int)mAuxBuffer);
3455}
3456
3457status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3458{
3459     audio_track_cblk_t* cblk = this->cblk();
3460     uint32_t framesReady;
3461     uint32_t framesReq = buffer->frameCount;
3462
3463     // Check if last stepServer failed, try to step now
3464     if (mFlags & TrackBase::STEPSERVER_FAILED) {
3465         if (!step())  goto getNextBuffer_exit;
3466         ALOGV("stepServer recovered");
3467         mFlags &= ~TrackBase::STEPSERVER_FAILED;
3468     }
3469
3470     framesReady = cblk->framesReady();
3471
3472     if (CC_LIKELY(framesReady)) {
3473        uint32_t s = cblk->server;
3474        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3475
3476        bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3477        if (framesReq > framesReady) {
3478            framesReq = framesReady;
3479        }
3480        if (s + framesReq > bufferEnd) {
3481            framesReq = bufferEnd - s;
3482        }
3483
3484         buffer->raw = getBuffer(s, framesReq);
3485         if (buffer->raw == NULL) goto getNextBuffer_exit;
3486
3487         buffer->frameCount = framesReq;
3488        return NO_ERROR;
3489     }
3490
3491getNextBuffer_exit:
3492     buffer->raw = NULL;
3493     buffer->frameCount = 0;
3494     ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3495     return NOT_ENOUGH_DATA;
3496}
3497
3498bool AudioFlinger::PlaybackThread::Track::isReady() const {
3499    if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
3500
3501    if (mCblk->framesReady() >= mCblk->frameCount ||
3502            (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3503        mFillingUpStatus = FS_FILLED;
3504        android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3505        return true;
3506    }
3507    return false;
3508}
3509
3510status_t AudioFlinger::PlaybackThread::Track::start()
3511{
3512    status_t status = NO_ERROR;
3513    ALOGV("start(%d), calling pid %d session %d",
3514            mName, IPCThreadState::self()->getCallingPid(), mSessionId);
3515    sp<ThreadBase> thread = mThread.promote();
3516    if (thread != 0) {
3517        Mutex::Autolock _l(thread->mLock);
3518        track_state state = mState;
3519        // here the track could be either new, or restarted
3520        // in both cases "unstop" the track
3521        if (mState == PAUSED) {
3522            mState = TrackBase::RESUMING;
3523            ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3524        } else {
3525            mState = TrackBase::ACTIVE;
3526            ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
3527        }
3528
3529        if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3530            thread->mLock.unlock();
3531            status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
3532            thread->mLock.lock();
3533
3534            // to track the speaker usage
3535            if (status == NO_ERROR) {
3536                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3537            }
3538        }
3539        if (status == NO_ERROR) {
3540            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3541            playbackThread->addTrack_l(this);
3542        } else {
3543            mState = state;
3544        }
3545    } else {
3546        status = BAD_VALUE;
3547    }
3548    return status;
3549}
3550
3551void AudioFlinger::PlaybackThread::Track::stop()
3552{
3553    ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
3554    sp<ThreadBase> thread = mThread.promote();
3555    if (thread != 0) {
3556        Mutex::Autolock _l(thread->mLock);
3557        track_state state = mState;
3558        if (mState > STOPPED) {
3559            mState = STOPPED;
3560            // If the track is not active (PAUSED and buffers full), flush buffers
3561            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3562            if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3563                reset();
3564            }
3565            ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3566        }
3567        if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3568            thread->mLock.unlock();
3569            AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
3570            thread->mLock.lock();
3571
3572            // to track the speaker usage
3573            addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
3574        }
3575    }
3576}
3577
3578void AudioFlinger::PlaybackThread::Track::pause()
3579{
3580    ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
3581    sp<ThreadBase> thread = mThread.promote();
3582    if (thread != 0) {
3583        Mutex::Autolock _l(thread->mLock);
3584        if (mState == ACTIVE || mState == RESUMING) {
3585            mState = PAUSING;
3586            ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3587            if (!isOutputTrack()) {
3588                thread->mLock.unlock();
3589                AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
3590                thread->mLock.lock();
3591
3592                // to track the speaker usage
3593                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
3594            }
3595        }
3596    }
3597}
3598
3599void AudioFlinger::PlaybackThread::Track::flush()
3600{
3601    ALOGV("flush(%d)", mName);
3602    sp<ThreadBase> thread = mThread.promote();
3603    if (thread != 0) {
3604        Mutex::Autolock _l(thread->mLock);
3605        if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3606            return;
3607        }
3608        // No point remaining in PAUSED state after a flush => go to
3609        // STOPPED state
3610        mState = STOPPED;
3611
3612        // do not reset the track if it is still in the process of being stopped or paused.
3613        // this will be done by prepareTracks_l() when the track is stopped.
3614        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3615        if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3616            reset();
3617        }
3618    }
3619}
3620
3621void AudioFlinger::PlaybackThread::Track::reset()
3622{
3623    // Do not reset twice to avoid discarding data written just after a flush and before
3624    // the audioflinger thread detects the track is stopped.
3625    if (!mResetDone) {
3626        TrackBase::reset();
3627        // Force underrun condition to avoid false underrun callback until first data is
3628        // written to buffer
3629        android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3630        android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
3631        mFillingUpStatus = FS_FILLING;
3632        mResetDone = true;
3633    }
3634}
3635
3636void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3637{
3638    mMute = muted;
3639}
3640
3641status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3642{
3643    status_t status = DEAD_OBJECT;
3644    sp<ThreadBase> thread = mThread.promote();
3645    if (thread != 0) {
3646       PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3647       status = playbackThread->attachAuxEffect(this, EffectId);
3648    }
3649    return status;
3650}
3651
3652void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3653{
3654    mAuxEffectId = EffectId;
3655    mAuxBuffer = buffer;
3656}
3657
3658// ----------------------------------------------------------------------------
3659
3660// RecordTrack constructor must be called with AudioFlinger::mLock held
3661AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3662            const wp<ThreadBase>& thread,
3663            const sp<Client>& client,
3664            uint32_t sampleRate,
3665            audio_format_t format,
3666            uint32_t channelMask,
3667            int frameCount,
3668            uint32_t flags,
3669            int sessionId)
3670    :   TrackBase(thread, client, sampleRate, format,
3671                  channelMask, frameCount, flags, 0, sessionId),
3672        mOverflow(false)
3673{
3674    if (mCblk != NULL) {
3675       ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
3676       if (format == AUDIO_FORMAT_PCM_16_BIT) {
3677           mCblk->frameSize = mChannelCount * sizeof(int16_t);
3678       } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
3679           mCblk->frameSize = mChannelCount * sizeof(int8_t);
3680       } else {
3681           mCblk->frameSize = sizeof(int8_t);
3682       }
3683    }
3684}
3685
3686AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3687{
3688    sp<ThreadBase> thread = mThread.promote();
3689    if (thread != 0) {
3690        AudioSystem::releaseInput(thread->id());
3691    }
3692}
3693
3694status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3695{
3696    audio_track_cblk_t* cblk = this->cblk();
3697    uint32_t framesAvail;
3698    uint32_t framesReq = buffer->frameCount;
3699
3700     // Check if last stepServer failed, try to step now
3701    if (mFlags & TrackBase::STEPSERVER_FAILED) {
3702        if (!step()) goto getNextBuffer_exit;
3703        ALOGV("stepServer recovered");
3704        mFlags &= ~TrackBase::STEPSERVER_FAILED;
3705    }
3706
3707    framesAvail = cblk->framesAvailable_l();
3708
3709    if (CC_LIKELY(framesAvail)) {
3710        uint32_t s = cblk->server;
3711        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3712
3713        if (framesReq > framesAvail) {
3714            framesReq = framesAvail;
3715        }
3716        if (s + framesReq > bufferEnd) {
3717            framesReq = bufferEnd - s;
3718        }
3719
3720        buffer->raw = getBuffer(s, framesReq);
3721        if (buffer->raw == NULL) goto getNextBuffer_exit;
3722
3723        buffer->frameCount = framesReq;
3724        return NO_ERROR;
3725    }
3726
3727getNextBuffer_exit:
3728    buffer->raw = NULL;
3729    buffer->frameCount = 0;
3730    return NOT_ENOUGH_DATA;
3731}
3732
3733status_t AudioFlinger::RecordThread::RecordTrack::start()
3734{
3735    sp<ThreadBase> thread = mThread.promote();
3736    if (thread != 0) {
3737        RecordThread *recordThread = (RecordThread *)thread.get();
3738        return recordThread->start(this);
3739    } else {
3740        return BAD_VALUE;
3741    }
3742}
3743
3744void AudioFlinger::RecordThread::RecordTrack::stop()
3745{
3746    sp<ThreadBase> thread = mThread.promote();
3747    if (thread != 0) {
3748        RecordThread *recordThread = (RecordThread *)thread.get();
3749        recordThread->stop(this);
3750        TrackBase::reset();
3751        // Force overerrun condition to avoid false overrun callback until first data is
3752        // read from buffer
3753        android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
3754    }
3755}
3756
3757void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3758{
3759    snprintf(buffer, size, "   %05d %03u 0x%08x %05d   %04u %01d %05u  %08x %08x\n",
3760            (mClient == 0) ? getpid() : mClient->pid(),
3761            mFormat,
3762            mChannelMask,
3763            mSessionId,
3764            mFrameCount,
3765            mState,
3766            mCblk->sampleRate,
3767            mCblk->server,
3768            mCblk->user);
3769}
3770
3771
3772// ----------------------------------------------------------------------------
3773
3774AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3775            const wp<ThreadBase>& thread,
3776            DuplicatingThread *sourceThread,
3777            uint32_t sampleRate,
3778            audio_format_t format,
3779            uint32_t channelMask,
3780            int frameCount)
3781    :   Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
3782    mActive(false), mSourceThread(sourceThread)
3783{
3784
3785    PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3786    if (mCblk != NULL) {
3787        mCblk->flags |= CBLK_DIRECTION_OUT;
3788        mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3789        mOutBuffer.frameCount = 0;
3790        playbackThread->mTracks.add(this);
3791        ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3792                "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3793                mCblk, mBuffer, mCblk->buffers,
3794                mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
3795    } else {
3796        ALOGW("Error creating output track on thread %p", playbackThread);
3797    }
3798}
3799
3800AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3801{
3802    clearBufferQueue();
3803}
3804
3805status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3806{
3807    status_t status = Track::start();
3808    if (status != NO_ERROR) {
3809        return status;
3810    }
3811
3812    mActive = true;
3813    mRetryCount = 127;
3814    return status;
3815}
3816
3817void AudioFlinger::PlaybackThread::OutputTrack::stop()
3818{
3819    Track::stop();
3820    clearBufferQueue();
3821    mOutBuffer.frameCount = 0;
3822    mActive = false;
3823}
3824
3825bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3826{
3827    Buffer *pInBuffer;
3828    Buffer inBuffer;
3829    uint32_t channelCount = mChannelCount;
3830    bool outputBufferFull = false;
3831    inBuffer.frameCount = frames;
3832    inBuffer.i16 = data;
3833
3834    uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3835
3836    if (!mActive && frames != 0) {
3837        start();
3838        sp<ThreadBase> thread = mThread.promote();
3839        if (thread != 0) {
3840            MixerThread *mixerThread = (MixerThread *)thread.get();
3841            if (mCblk->frameCount > frames){
3842                if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3843                    uint32_t startFrames = (mCblk->frameCount - frames);
3844                    pInBuffer = new Buffer;
3845                    pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3846                    pInBuffer->frameCount = startFrames;
3847                    pInBuffer->i16 = pInBuffer->mBuffer;
3848                    memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3849                    mBufferQueue.add(pInBuffer);
3850                } else {
3851                    ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
3852                }
3853            }
3854        }
3855    }
3856
3857    while (waitTimeLeftMs) {
3858        // First write pending buffers, then new data
3859        if (mBufferQueue.size()) {
3860            pInBuffer = mBufferQueue.itemAt(0);
3861        } else {
3862            pInBuffer = &inBuffer;
3863        }
3864
3865        if (pInBuffer->frameCount == 0) {
3866            break;
3867        }
3868
3869        if (mOutBuffer.frameCount == 0) {
3870            mOutBuffer.frameCount = pInBuffer->frameCount;
3871            nsecs_t startTime = systemTime();
3872            if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
3873                ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
3874                outputBufferFull = true;
3875                break;
3876            }
3877            uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3878            if (waitTimeLeftMs >= waitTimeMs) {
3879                waitTimeLeftMs -= waitTimeMs;
3880            } else {
3881                waitTimeLeftMs = 0;
3882            }
3883        }
3884
3885        uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3886        memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3887        mCblk->stepUser(outFrames);
3888        pInBuffer->frameCount -= outFrames;
3889        pInBuffer->i16 += outFrames * channelCount;
3890        mOutBuffer.frameCount -= outFrames;
3891        mOutBuffer.i16 += outFrames * channelCount;
3892
3893        if (pInBuffer->frameCount == 0) {
3894            if (mBufferQueue.size()) {
3895                mBufferQueue.removeAt(0);
3896                delete [] pInBuffer->mBuffer;
3897                delete pInBuffer;
3898                ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3899            } else {
3900                break;
3901            }
3902        }
3903    }
3904
3905    // If we could not write all frames, allocate a buffer and queue it for next time.
3906    if (inBuffer.frameCount) {
3907        sp<ThreadBase> thread = mThread.promote();
3908        if (thread != 0 && !thread->standby()) {
3909            if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3910                pInBuffer = new Buffer;
3911                pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3912                pInBuffer->frameCount = inBuffer.frameCount;
3913                pInBuffer->i16 = pInBuffer->mBuffer;
3914                memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3915                mBufferQueue.add(pInBuffer);
3916                ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3917            } else {
3918                ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3919            }
3920        }
3921    }
3922
3923    // Calling write() with a 0 length buffer, means that no more data will be written:
3924    // If no more buffers are pending, fill output track buffer to make sure it is started
3925    // by output mixer.
3926    if (frames == 0 && mBufferQueue.size() == 0) {
3927        if (mCblk->user < mCblk->frameCount) {
3928            frames = mCblk->frameCount - mCblk->user;
3929            pInBuffer = new Buffer;
3930            pInBuffer->mBuffer = new int16_t[frames * channelCount];
3931            pInBuffer->frameCount = frames;
3932            pInBuffer->i16 = pInBuffer->mBuffer;
3933            memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3934            mBufferQueue.add(pInBuffer);
3935        } else if (mActive) {
3936            stop();
3937        }
3938    }
3939
3940    return outputBufferFull;
3941}
3942
3943status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3944{
3945    int active;
3946    status_t result;
3947    audio_track_cblk_t* cblk = mCblk;
3948    uint32_t framesReq = buffer->frameCount;
3949
3950//    ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
3951    buffer->frameCount  = 0;
3952
3953    uint32_t framesAvail = cblk->framesAvailable();
3954
3955
3956    if (framesAvail == 0) {
3957        Mutex::Autolock _l(cblk->lock);
3958        goto start_loop_here;
3959        while (framesAvail == 0) {
3960            active = mActive;
3961            if (CC_UNLIKELY(!active)) {
3962                ALOGV("Not active and NO_MORE_BUFFERS");
3963                return NO_MORE_BUFFERS;
3964            }
3965            result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3966            if (result != NO_ERROR) {
3967                return NO_MORE_BUFFERS;
3968            }
3969            // read the server count again
3970        start_loop_here:
3971            framesAvail = cblk->framesAvailable_l();
3972        }
3973    }
3974
3975//    if (framesAvail < framesReq) {
3976//        return NO_MORE_BUFFERS;
3977//    }
3978
3979    if (framesReq > framesAvail) {
3980        framesReq = framesAvail;
3981    }
3982
3983    uint32_t u = cblk->user;
3984    uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3985
3986    if (u + framesReq > bufferEnd) {
3987        framesReq = bufferEnd - u;
3988    }
3989
3990    buffer->frameCount  = framesReq;
3991    buffer->raw         = (void *)cblk->buffer(u);
3992    return NO_ERROR;
3993}
3994
3995
3996void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3997{
3998    size_t size = mBufferQueue.size();
3999    Buffer *pBuffer;
4000
4001    for (size_t i = 0; i < size; i++) {
4002        pBuffer = mBufferQueue.itemAt(i);
4003        delete [] pBuffer->mBuffer;
4004        delete pBuffer;
4005    }
4006    mBufferQueue.clear();
4007}
4008
4009// ----------------------------------------------------------------------------
4010
4011AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4012    :   RefBase(),
4013        mAudioFlinger(audioFlinger),
4014        mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4015        mPid(pid)
4016{
4017    // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4018}
4019
4020// Client destructor must be called with AudioFlinger::mLock held
4021AudioFlinger::Client::~Client()
4022{
4023    mAudioFlinger->removeClient_l(mPid);
4024}
4025
4026sp<MemoryDealer> AudioFlinger::Client::heap() const
4027{
4028    return mMemoryDealer;
4029}
4030
4031// ----------------------------------------------------------------------------
4032
4033AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4034                                                     const sp<IAudioFlingerClient>& client,
4035                                                     pid_t pid)
4036    : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
4037{
4038}
4039
4040AudioFlinger::NotificationClient::~NotificationClient()
4041{
4042}
4043
4044void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4045{
4046    sp<NotificationClient> keep(this);
4047    {
4048        mAudioFlinger->removeNotificationClient(mPid);
4049    }
4050}
4051
4052// ----------------------------------------------------------------------------
4053
4054AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4055    : BnAudioTrack(),
4056      mTrack(track)
4057{
4058}
4059
4060AudioFlinger::TrackHandle::~TrackHandle() {
4061    // just stop the track on deletion, associated resources
4062    // will be freed from the main thread once all pending buffers have
4063    // been played. Unless it's not in the active track list, in which
4064    // case we free everything now...
4065    mTrack->destroy();
4066}
4067
4068sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4069    return mTrack->getCblk();
4070}
4071
4072status_t AudioFlinger::TrackHandle::start() {
4073    return mTrack->start();
4074}
4075
4076void AudioFlinger::TrackHandle::stop() {
4077    mTrack->stop();
4078}
4079
4080void AudioFlinger::TrackHandle::flush() {
4081    mTrack->flush();
4082}
4083
4084void AudioFlinger::TrackHandle::mute(bool e) {
4085    mTrack->mute(e);
4086}
4087
4088void AudioFlinger::TrackHandle::pause() {
4089    mTrack->pause();
4090}
4091
4092status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4093{
4094    return mTrack->attachAuxEffect(EffectId);
4095}
4096
4097status_t AudioFlinger::TrackHandle::onTransact(
4098    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4099{
4100    return BnAudioTrack::onTransact(code, data, reply, flags);
4101}
4102
4103// ----------------------------------------------------------------------------
4104
4105sp<IAudioRecord> AudioFlinger::openRecord(
4106        pid_t pid,
4107        audio_io_handle_t input,
4108        uint32_t sampleRate,
4109        audio_format_t format,
4110        uint32_t channelMask,
4111        int frameCount,
4112        uint32_t flags,
4113        int *sessionId,
4114        status_t *status)
4115{
4116    sp<RecordThread::RecordTrack> recordTrack;
4117    sp<RecordHandle> recordHandle;
4118    sp<Client> client;
4119    status_t lStatus;
4120    RecordThread *thread;
4121    size_t inFrameCount;
4122    int lSessionId;
4123
4124    // check calling permissions
4125    if (!recordingAllowed()) {
4126        lStatus = PERMISSION_DENIED;
4127        goto Exit;
4128    }
4129
4130    // add client to list
4131    { // scope for mLock
4132        Mutex::Autolock _l(mLock);
4133        thread = checkRecordThread_l(input);
4134        if (thread == NULL) {
4135            lStatus = BAD_VALUE;
4136            goto Exit;
4137        }
4138
4139        client = registerPid_l(pid);
4140
4141        // If no audio session id is provided, create one here
4142        if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
4143            lSessionId = *sessionId;
4144        } else {
4145            lSessionId = nextUniqueId();
4146            if (sessionId != NULL) {
4147                *sessionId = lSessionId;
4148            }
4149        }
4150        // create new record track. The record track uses one track in mHardwareMixerThread by convention.
4151        recordTrack = thread->createRecordTrack_l(client,
4152                                                sampleRate,
4153                                                format,
4154                                                channelMask,
4155                                                frameCount,
4156                                                flags,
4157                                                lSessionId,
4158                                                &lStatus);
4159    }
4160    if (lStatus != NO_ERROR) {
4161        // remove local strong reference to Client before deleting the RecordTrack so that the Client
4162        // destructor is called by the TrackBase destructor with mLock held
4163        client.clear();
4164        recordTrack.clear();
4165        goto Exit;
4166    }
4167
4168    // return to handle to client
4169    recordHandle = new RecordHandle(recordTrack);
4170    lStatus = NO_ERROR;
4171
4172Exit:
4173    if (status) {
4174        *status = lStatus;
4175    }
4176    return recordHandle;
4177}
4178
4179// ----------------------------------------------------------------------------
4180
4181AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4182    : BnAudioRecord(),
4183    mRecordTrack(recordTrack)
4184{
4185}
4186
4187AudioFlinger::RecordHandle::~RecordHandle() {
4188    stop();
4189}
4190
4191sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4192    return mRecordTrack->getCblk();
4193}
4194
4195status_t AudioFlinger::RecordHandle::start() {
4196    ALOGV("RecordHandle::start()");
4197    return mRecordTrack->start();
4198}
4199
4200void AudioFlinger::RecordHandle::stop() {
4201    ALOGV("RecordHandle::stop()");
4202    mRecordTrack->stop();
4203}
4204
4205status_t AudioFlinger::RecordHandle::onTransact(
4206    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4207{
4208    return BnAudioRecord::onTransact(code, data, reply, flags);
4209}
4210
4211// ----------------------------------------------------------------------------
4212
4213AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4214                                         AudioStreamIn *input,
4215                                         uint32_t sampleRate,
4216                                         uint32_t channels,
4217                                         audio_io_handle_t id,
4218                                         uint32_t device) :
4219    ThreadBase(audioFlinger, id, device, RECORD),
4220    mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4221    // mRsmpInIndex and mInputBytes set by readInputParameters()
4222    mReqChannelCount(popcount(channels)),
4223    mReqSampleRate(sampleRate)
4224    // mBytesRead is only meaningful while active, and so is cleared in start()
4225    // (but might be better to also clear here for dump?)
4226{
4227    snprintf(mName, kNameLength, "AudioIn_%d", id);
4228
4229    readInputParameters();
4230}
4231
4232
4233AudioFlinger::RecordThread::~RecordThread()
4234{
4235    delete[] mRsmpInBuffer;
4236    delete mResampler;
4237    delete[] mRsmpOutBuffer;
4238}
4239
4240void AudioFlinger::RecordThread::onFirstRef()
4241{
4242    run(mName, PRIORITY_URGENT_AUDIO);
4243}
4244
4245status_t AudioFlinger::RecordThread::readyToRun()
4246{
4247    status_t status = initCheck();
4248    ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4249    return status;
4250}
4251
4252bool AudioFlinger::RecordThread::threadLoop()
4253{
4254    AudioBufferProvider::Buffer buffer;
4255    sp<RecordTrack> activeTrack;
4256    Vector< sp<EffectChain> > effectChains;
4257
4258    nsecs_t lastWarning = 0;
4259
4260    acquireWakeLock();
4261
4262    // start recording
4263    while (!exitPending()) {
4264
4265        processConfigEvents();
4266
4267        { // scope for mLock
4268            Mutex::Autolock _l(mLock);
4269            checkForNewParameters_l();
4270            if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4271                if (!mStandby) {
4272                    mInput->stream->common.standby(&mInput->stream->common);
4273                    mStandby = true;
4274                }
4275
4276                if (exitPending()) break;
4277
4278                releaseWakeLock_l();
4279                ALOGV("RecordThread: loop stopping");
4280                // go to sleep
4281                mWaitWorkCV.wait(mLock);
4282                ALOGV("RecordThread: loop starting");
4283                acquireWakeLock_l();
4284                continue;
4285            }
4286            if (mActiveTrack != 0) {
4287                if (mActiveTrack->mState == TrackBase::PAUSING) {
4288                    if (!mStandby) {
4289                        mInput->stream->common.standby(&mInput->stream->common);
4290                        mStandby = true;
4291                    }
4292                    mActiveTrack.clear();
4293                    mStartStopCond.broadcast();
4294                } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4295                    if (mReqChannelCount != mActiveTrack->channelCount()) {
4296                        mActiveTrack.clear();
4297                        mStartStopCond.broadcast();
4298                    } else if (mBytesRead != 0) {
4299                        // record start succeeds only if first read from audio input
4300                        // succeeds
4301                        if (mBytesRead > 0) {
4302                            mActiveTrack->mState = TrackBase::ACTIVE;
4303                        } else {
4304                            mActiveTrack.clear();
4305                        }
4306                        mStartStopCond.broadcast();
4307                    }
4308                    mStandby = false;
4309                }
4310            }
4311            lockEffectChains_l(effectChains);
4312        }
4313
4314        if (mActiveTrack != 0) {
4315            if (mActiveTrack->mState != TrackBase::ACTIVE &&
4316                mActiveTrack->mState != TrackBase::RESUMING) {
4317                unlockEffectChains(effectChains);
4318                usleep(kRecordThreadSleepUs);
4319                continue;
4320            }
4321            for (size_t i = 0; i < effectChains.size(); i ++) {
4322                effectChains[i]->process_l();
4323            }
4324
4325            buffer.frameCount = mFrameCount;
4326            if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4327                size_t framesOut = buffer.frameCount;
4328                if (mResampler == NULL) {
4329                    // no resampling
4330                    while (framesOut) {
4331                        size_t framesIn = mFrameCount - mRsmpInIndex;
4332                        if (framesIn) {
4333                            int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4334                            int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4335                            if (framesIn > framesOut)
4336                                framesIn = framesOut;
4337                            mRsmpInIndex += framesIn;
4338                            framesOut -= framesIn;
4339                            if ((int)mChannelCount == mReqChannelCount ||
4340                                mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4341                                memcpy(dst, src, framesIn * mFrameSize);
4342                            } else {
4343                                int16_t *src16 = (int16_t *)src;
4344                                int16_t *dst16 = (int16_t *)dst;
4345                                if (mChannelCount == 1) {
4346                                    while (framesIn--) {
4347                                        *dst16++ = *src16;
4348                                        *dst16++ = *src16++;
4349                                    }
4350                                } else {
4351                                    while (framesIn--) {
4352                                        *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4353                                        src16 += 2;
4354                                    }
4355                                }
4356                            }
4357                        }
4358                        if (framesOut && mFrameCount == mRsmpInIndex) {
4359                            if (framesOut == mFrameCount &&
4360                                ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
4361                                mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
4362                                framesOut = 0;
4363                            } else {
4364                                mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
4365                                mRsmpInIndex = 0;
4366                            }
4367                            if (mBytesRead < 0) {
4368                                ALOGE("Error reading audio input");
4369                                if (mActiveTrack->mState == TrackBase::ACTIVE) {
4370                                    // Force input into standby so that it tries to
4371                                    // recover at next read attempt
4372                                    mInput->stream->common.standby(&mInput->stream->common);
4373                                    usleep(kRecordThreadSleepUs);
4374                                }
4375                                mRsmpInIndex = mFrameCount;
4376                                framesOut = 0;
4377                                buffer.frameCount = 0;
4378                            }
4379                        }
4380                    }
4381                } else {
4382                    // resampling
4383
4384                    memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4385                    // alter output frame count as if we were expecting stereo samples
4386                    if (mChannelCount == 1 && mReqChannelCount == 1) {
4387                        framesOut >>= 1;
4388                    }
4389                    mResampler->resample(mRsmpOutBuffer, framesOut, this);
4390                    // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4391                    // are 32 bit aligned which should be always true.
4392                    if (mChannelCount == 2 && mReqChannelCount == 1) {
4393                        ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4394                        // the resampler always outputs stereo samples: do post stereo to mono conversion
4395                        int16_t *src = (int16_t *)mRsmpOutBuffer;
4396                        int16_t *dst = buffer.i16;
4397                        while (framesOut--) {
4398                            *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4399                            src += 2;
4400                        }
4401                    } else {
4402                        ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4403                    }
4404
4405                }
4406                mActiveTrack->releaseBuffer(&buffer);
4407                mActiveTrack->overflow();
4408            }
4409            // client isn't retrieving buffers fast enough
4410            else {
4411                if (!mActiveTrack->setOverflow()) {
4412                    nsecs_t now = systemTime();
4413                    if ((now - lastWarning) > kWarningThrottleNs) {
4414                        ALOGW("RecordThread: buffer overflow");
4415                        lastWarning = now;
4416                    }
4417                }
4418                // Release the processor for a while before asking for a new buffer.
4419                // This will give the application more chance to read from the buffer and
4420                // clear the overflow.
4421                usleep(kRecordThreadSleepUs);
4422            }
4423        }
4424        // enable changes in effect chain
4425        unlockEffectChains(effectChains);
4426        effectChains.clear();
4427    }
4428
4429    if (!mStandby) {
4430        mInput->stream->common.standby(&mInput->stream->common);
4431    }
4432    mActiveTrack.clear();
4433
4434    mStartStopCond.broadcast();
4435
4436    releaseWakeLock();
4437
4438    ALOGV("RecordThread %p exiting", this);
4439    return false;
4440}
4441
4442
4443sp<AudioFlinger::RecordThread::RecordTrack>  AudioFlinger::RecordThread::createRecordTrack_l(
4444        const sp<AudioFlinger::Client>& client,
4445        uint32_t sampleRate,
4446        audio_format_t format,
4447        int channelMask,
4448        int frameCount,
4449        uint32_t flags,
4450        int sessionId,
4451        status_t *status)
4452{
4453    sp<RecordTrack> track;
4454    status_t lStatus;
4455
4456    lStatus = initCheck();
4457    if (lStatus != NO_ERROR) {
4458        ALOGE("Audio driver not initialized.");
4459        goto Exit;
4460    }
4461
4462    { // scope for mLock
4463        Mutex::Autolock _l(mLock);
4464
4465        track = new RecordTrack(this, client, sampleRate,
4466                      format, channelMask, frameCount, flags, sessionId);
4467
4468        if (track->getCblk() == 0) {
4469            lStatus = NO_MEMORY;
4470            goto Exit;
4471        }
4472
4473        mTrack = track.get();
4474        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4475        bool suspend = audio_is_bluetooth_sco_device(
4476                (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
4477        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4478        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
4479    }
4480    lStatus = NO_ERROR;
4481
4482Exit:
4483    if (status) {
4484        *status = lStatus;
4485    }
4486    return track;
4487}
4488
4489status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4490{
4491    ALOGV("RecordThread::start");
4492    sp <ThreadBase> strongMe = this;
4493    status_t status = NO_ERROR;
4494    {
4495        AutoMutex lock(mLock);
4496        if (mActiveTrack != 0) {
4497            if (recordTrack != mActiveTrack.get()) {
4498                status = -EBUSY;
4499            } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4500                mActiveTrack->mState = TrackBase::ACTIVE;
4501            }
4502            return status;
4503        }
4504
4505        recordTrack->mState = TrackBase::IDLE;
4506        mActiveTrack = recordTrack;
4507        mLock.unlock();
4508        status_t status = AudioSystem::startInput(mId);
4509        mLock.lock();
4510        if (status != NO_ERROR) {
4511            mActiveTrack.clear();
4512            return status;
4513        }
4514        mRsmpInIndex = mFrameCount;
4515        mBytesRead = 0;
4516        if (mResampler != NULL) {
4517            mResampler->reset();
4518        }
4519        mActiveTrack->mState = TrackBase::RESUMING;
4520        // signal thread to start
4521        ALOGV("Signal record thread");
4522        mWaitWorkCV.signal();
4523        // do not wait for mStartStopCond if exiting
4524        if (exitPending()) {
4525            mActiveTrack.clear();
4526            status = INVALID_OPERATION;
4527            goto startError;
4528        }
4529        mStartStopCond.wait(mLock);
4530        if (mActiveTrack == 0) {
4531            ALOGV("Record failed to start");
4532            status = BAD_VALUE;
4533            goto startError;
4534        }
4535        ALOGV("Record started OK");
4536        return status;
4537    }
4538startError:
4539    AudioSystem::stopInput(mId);
4540    return status;
4541}
4542
4543void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4544    ALOGV("RecordThread::stop");
4545    sp <ThreadBase> strongMe = this;
4546    {
4547        AutoMutex lock(mLock);
4548        if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4549            mActiveTrack->mState = TrackBase::PAUSING;
4550            // do not wait for mStartStopCond if exiting
4551            if (exitPending()) {
4552                return;
4553            }
4554            mStartStopCond.wait(mLock);
4555            // if we have been restarted, recordTrack == mActiveTrack.get() here
4556            if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4557                mLock.unlock();
4558                AudioSystem::stopInput(mId);
4559                mLock.lock();
4560                ALOGV("Record stopped OK");
4561            }
4562        }
4563    }
4564}
4565
4566status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4567{
4568    const size_t SIZE = 256;
4569    char buffer[SIZE];
4570    String8 result;
4571
4572    snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4573    result.append(buffer);
4574
4575    if (mActiveTrack != 0) {
4576        result.append("Active Track:\n");
4577        result.append("   Clien Fmt Chn mask   Session Buf  S SRate  Serv     User\n");
4578        mActiveTrack->dump(buffer, SIZE);
4579        result.append(buffer);
4580
4581        snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4582        result.append(buffer);
4583        snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4584        result.append(buffer);
4585        snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4586        result.append(buffer);
4587        snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4588        result.append(buffer);
4589        snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4590        result.append(buffer);
4591
4592
4593    } else {
4594        result.append("No record client\n");
4595    }
4596    write(fd, result.string(), result.size());
4597
4598    dumpBase(fd, args);
4599    dumpEffectChains(fd, args);
4600
4601    return NO_ERROR;
4602}
4603
4604status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4605{
4606    size_t framesReq = buffer->frameCount;
4607    size_t framesReady = mFrameCount - mRsmpInIndex;
4608    int channelCount;
4609
4610    if (framesReady == 0) {
4611        mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
4612        if (mBytesRead < 0) {
4613            ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4614            if (mActiveTrack->mState == TrackBase::ACTIVE) {
4615                // Force input into standby so that it tries to
4616                // recover at next read attempt
4617                mInput->stream->common.standby(&mInput->stream->common);
4618                usleep(kRecordThreadSleepUs);
4619            }
4620            buffer->raw = NULL;
4621            buffer->frameCount = 0;
4622            return NOT_ENOUGH_DATA;
4623        }
4624        mRsmpInIndex = 0;
4625        framesReady = mFrameCount;
4626    }
4627
4628    if (framesReq > framesReady) {
4629        framesReq = framesReady;
4630    }
4631
4632    if (mChannelCount == 1 && mReqChannelCount == 2) {
4633        channelCount = 1;
4634    } else {
4635        channelCount = 2;
4636    }
4637    buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4638    buffer->frameCount = framesReq;
4639    return NO_ERROR;
4640}
4641
4642void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4643{
4644    mRsmpInIndex += buffer->frameCount;
4645    buffer->frameCount = 0;
4646}
4647
4648bool AudioFlinger::RecordThread::checkForNewParameters_l()
4649{
4650    bool reconfig = false;
4651
4652    while (!mNewParameters.isEmpty()) {
4653        status_t status = NO_ERROR;
4654        String8 keyValuePair = mNewParameters[0];
4655        AudioParameter param = AudioParameter(keyValuePair);
4656        int value;
4657        audio_format_t reqFormat = mFormat;
4658        int reqSamplingRate = mReqSampleRate;
4659        int reqChannelCount = mReqChannelCount;
4660
4661        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4662            reqSamplingRate = value;
4663            reconfig = true;
4664        }
4665        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4666            reqFormat = (audio_format_t) value;
4667            reconfig = true;
4668        }
4669        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4670            reqChannelCount = popcount(value);
4671            reconfig = true;
4672        }
4673        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4674            // do not accept frame count changes if tracks are open as the track buffer
4675            // size depends on frame count and correct behavior would not be garantied
4676            // if frame count is changed after track creation
4677            if (mActiveTrack != 0) {
4678                status = INVALID_OPERATION;
4679            } else {
4680                reconfig = true;
4681            }
4682        }
4683        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4684            // forward device change to effects that have requested to be
4685            // aware of attached audio device.
4686            for (size_t i = 0; i < mEffectChains.size(); i++) {
4687                mEffectChains[i]->setDevice_l(value);
4688            }
4689            // store input device and output device but do not forward output device to audio HAL.
4690            // Note that status is ignored by the caller for output device
4691            // (see AudioFlinger::setParameters()
4692            if (value & AUDIO_DEVICE_OUT_ALL) {
4693                mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4694                status = BAD_VALUE;
4695            } else {
4696                mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
4697                // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4698                if (mTrack != NULL) {
4699                    bool suspend = audio_is_bluetooth_sco_device(
4700                            (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
4701                    setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4702                    setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4703                }
4704            }
4705            mDevice |= (uint32_t)value;
4706        }
4707        if (status == NO_ERROR) {
4708            status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
4709            if (status == INVALID_OPERATION) {
4710               mInput->stream->common.standby(&mInput->stream->common);
4711               status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
4712            }
4713            if (reconfig) {
4714                if (status == BAD_VALUE &&
4715                    reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
4716                    reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
4717                    ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4718                    (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
4719                    (reqChannelCount < 3)) {
4720                    status = NO_ERROR;
4721                }
4722                if (status == NO_ERROR) {
4723                    readInputParameters();
4724                    sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4725                }
4726            }
4727        }
4728
4729        mNewParameters.removeAt(0);
4730
4731        mParamStatus = status;
4732        mParamCond.signal();
4733        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4734        // already timed out waiting for the status and will never signal the condition.
4735        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
4736    }
4737    return reconfig;
4738}
4739
4740String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4741{
4742    char *s;
4743    String8 out_s8 = String8();
4744
4745    Mutex::Autolock _l(mLock);
4746    if (initCheck() != NO_ERROR) {
4747        return out_s8;
4748    }
4749
4750    s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
4751    out_s8 = String8(s);
4752    free(s);
4753    return out_s8;
4754}
4755
4756void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4757    AudioSystem::OutputDescriptor desc;
4758    void *param2 = NULL;
4759
4760    switch (event) {
4761    case AudioSystem::INPUT_OPENED:
4762    case AudioSystem::INPUT_CONFIG_CHANGED:
4763        desc.channels = mChannelMask;
4764        desc.samplingRate = mSampleRate;
4765        desc.format = mFormat;
4766        desc.frameCount = mFrameCount;
4767        desc.latency = 0;
4768        param2 = &desc;
4769        break;
4770
4771    case AudioSystem::INPUT_CLOSED:
4772    default:
4773        break;
4774    }
4775    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4776}
4777
4778void AudioFlinger::RecordThread::readInputParameters()
4779{
4780    delete mRsmpInBuffer;
4781    // mRsmpInBuffer is always assigned a new[] below
4782    delete mRsmpOutBuffer;
4783    mRsmpOutBuffer = NULL;
4784    delete mResampler;
4785    mResampler = NULL;
4786
4787    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
4788    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4789    mChannelCount = (uint16_t)popcount(mChannelMask);
4790    mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4791    mFrameSize = audio_stream_frame_size(&mInput->stream->common);
4792    mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
4793    mFrameCount = mInputBytes / mFrameSize;
4794    mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4795
4796    if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4797    {
4798        int channelCount;
4799         // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4800         // stereo to mono post process as the resampler always outputs stereo.
4801        if (mChannelCount == 1 && mReqChannelCount == 2) {
4802            channelCount = 1;
4803        } else {
4804            channelCount = 2;
4805        }
4806        mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4807        mResampler->setSampleRate(mSampleRate);
4808        mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4809        mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4810
4811        // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4812        if (mChannelCount == 1 && mReqChannelCount == 1) {
4813            mFrameCount >>= 1;
4814        }
4815
4816    }
4817    mRsmpInIndex = mFrameCount;
4818}
4819
4820unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4821{
4822    Mutex::Autolock _l(mLock);
4823    if (initCheck() != NO_ERROR) {
4824        return 0;
4825    }
4826
4827    return mInput->stream->get_input_frames_lost(mInput->stream);
4828}
4829
4830uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4831{
4832    Mutex::Autolock _l(mLock);
4833    uint32_t result = 0;
4834    if (getEffectChain_l(sessionId) != 0) {
4835        result = EFFECT_SESSION;
4836    }
4837
4838    if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4839        result |= TRACK_SESSION;
4840    }
4841
4842    return result;
4843}
4844
4845AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4846{
4847    Mutex::Autolock _l(mLock);
4848    return mTrack;
4849}
4850
4851AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
4852{
4853    Mutex::Autolock _l(mLock);
4854    return mInput;
4855}
4856
4857AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4858{
4859    Mutex::Autolock _l(mLock);
4860    AudioStreamIn *input = mInput;
4861    mInput = NULL;
4862    return input;
4863}
4864
4865// this method must always be called either with ThreadBase mLock held or inside the thread loop
4866audio_stream_t* AudioFlinger::RecordThread::stream()
4867{
4868    if (mInput == NULL) {
4869        return NULL;
4870    }
4871    return &mInput->stream->common;
4872}
4873
4874
4875// ----------------------------------------------------------------------------
4876
4877audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
4878                                uint32_t *pSamplingRate,
4879                                audio_format_t *pFormat,
4880                                uint32_t *pChannels,
4881                                uint32_t *pLatencyMs,
4882                                uint32_t flags)
4883{
4884    status_t status;
4885    PlaybackThread *thread = NULL;
4886    mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4887    uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4888    audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
4889    uint32_t channels = pChannels ? *pChannels : 0;
4890    uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
4891    audio_stream_out_t *outStream;
4892    audio_hw_device_t *outHwDev;
4893
4894    ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4895            pDevices ? *pDevices : 0,
4896            samplingRate,
4897            format,
4898            channels,
4899            flags);
4900
4901    if (pDevices == NULL || *pDevices == 0) {
4902        return 0;
4903    }
4904
4905    Mutex::Autolock _l(mLock);
4906
4907    outHwDev = findSuitableHwDev_l(*pDevices);
4908    if (outHwDev == NULL)
4909        return 0;
4910
4911    status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
4912                                          &channels, &samplingRate, &outStream);
4913    ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
4914            outStream,
4915            samplingRate,
4916            format,
4917            channels,
4918            status);
4919
4920    mHardwareStatus = AUDIO_HW_IDLE;
4921    if (outStream != NULL) {
4922        AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
4923        audio_io_handle_t id = nextUniqueId();
4924
4925        if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4926            (format != AUDIO_FORMAT_PCM_16_BIT) ||
4927            (channels != AUDIO_CHANNEL_OUT_STEREO)) {
4928            thread = new DirectOutputThread(this, output, id, *pDevices);
4929            ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4930        } else {
4931            thread = new MixerThread(this, output, id, *pDevices);
4932            ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
4933        }
4934        mPlaybackThreads.add(id, thread);
4935
4936        if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
4937        if (pFormat != NULL) *pFormat = format;
4938        if (pChannels != NULL) *pChannels = channels;
4939        if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
4940
4941        // notify client processes of the new output creation
4942        thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4943        return id;
4944    }
4945
4946    return 0;
4947}
4948
4949audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
4950        audio_io_handle_t output2)
4951{
4952    Mutex::Autolock _l(mLock);
4953    MixerThread *thread1 = checkMixerThread_l(output1);
4954    MixerThread *thread2 = checkMixerThread_l(output2);
4955
4956    if (thread1 == NULL || thread2 == NULL) {
4957        ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4958        return 0;
4959    }
4960
4961    audio_io_handle_t id = nextUniqueId();
4962    DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4963    thread->addOutputTrack(thread2);
4964    mPlaybackThreads.add(id, thread);
4965    // notify client processes of the new output creation
4966    thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4967    return id;
4968}
4969
4970status_t AudioFlinger::closeOutput(audio_io_handle_t output)
4971{
4972    // keep strong reference on the playback thread so that
4973    // it is not destroyed while exit() is executed
4974    sp <PlaybackThread> thread;
4975    {
4976        Mutex::Autolock _l(mLock);
4977        thread = checkPlaybackThread_l(output);
4978        if (thread == NULL) {
4979            return BAD_VALUE;
4980        }
4981
4982        ALOGV("closeOutput() %d", output);
4983
4984        if (thread->type() == ThreadBase::MIXER) {
4985            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4986                if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
4987                    DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4988                    dupThread->removeOutputTrack((MixerThread *)thread.get());
4989                }
4990            }
4991        }
4992        void *param2 = NULL;
4993        audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4994        mPlaybackThreads.removeItem(output);
4995    }
4996    thread->exit();
4997    // The thread entity (active unit of execution) is no longer running here,
4998    // but the ThreadBase container still exists.
4999
5000    if (thread->type() != ThreadBase::DUPLICATING) {
5001        AudioStreamOut *out = thread->clearOutput();
5002        assert(out != NULL);
5003        // from now on thread->mOutput is NULL
5004        out->hwDev->close_output_stream(out->hwDev, out->stream);
5005        delete out;
5006    }
5007    return NO_ERROR;
5008}
5009
5010status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
5011{
5012    Mutex::Autolock _l(mLock);
5013    PlaybackThread *thread = checkPlaybackThread_l(output);
5014
5015    if (thread == NULL) {
5016        return BAD_VALUE;
5017    }
5018
5019    ALOGV("suspendOutput() %d", output);
5020    thread->suspend();
5021
5022    return NO_ERROR;
5023}
5024
5025status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
5026{
5027    Mutex::Autolock _l(mLock);
5028    PlaybackThread *thread = checkPlaybackThread_l(output);
5029
5030    if (thread == NULL) {
5031        return BAD_VALUE;
5032    }
5033
5034    ALOGV("restoreOutput() %d", output);
5035
5036    thread->restore();
5037
5038    return NO_ERROR;
5039}
5040
5041audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
5042                                uint32_t *pSamplingRate,
5043                                audio_format_t *pFormat,
5044                                uint32_t *pChannels,
5045                                audio_in_acoustics_t acoustics)
5046{
5047    status_t status;
5048    RecordThread *thread = NULL;
5049    uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5050    audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
5051    uint32_t channels = pChannels ? *pChannels : 0;
5052    uint32_t reqSamplingRate = samplingRate;
5053    audio_format_t reqFormat = format;
5054    uint32_t reqChannels = channels;
5055    audio_stream_in_t *inStream;
5056    audio_hw_device_t *inHwDev;
5057
5058    if (pDevices == NULL || *pDevices == 0) {
5059        return 0;
5060    }
5061
5062    Mutex::Autolock _l(mLock);
5063
5064    inHwDev = findSuitableHwDev_l(*pDevices);
5065    if (inHwDev == NULL)
5066        return 0;
5067
5068    status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
5069                                        &channels, &samplingRate,
5070                                        acoustics,
5071                                        &inStream);
5072    ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
5073            inStream,
5074            samplingRate,
5075            format,
5076            channels,
5077            acoustics,
5078            status);
5079
5080    // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5081    // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5082    // or stereo to mono conversions on 16 bit PCM inputs.
5083    if (inStream == NULL && status == BAD_VALUE &&
5084        reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
5085        (samplingRate <= 2 * reqSamplingRate) &&
5086        (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
5087        ALOGV("openInput() reopening with proposed sampling rate and channels");
5088        status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
5089                                            &channels, &samplingRate,
5090                                            acoustics,
5091                                            &inStream);
5092    }
5093
5094    if (inStream != NULL) {
5095        AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5096
5097        audio_io_handle_t id = nextUniqueId();
5098        // Start record thread
5099        // RecorThread require both input and output device indication to forward to audio
5100        // pre processing modules
5101        uint32_t device = (*pDevices) | primaryOutputDevice_l();
5102        thread = new RecordThread(this,
5103                                  input,
5104                                  reqSamplingRate,
5105                                  reqChannels,
5106                                  id,
5107                                  device);
5108        mRecordThreads.add(id, thread);
5109        ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
5110        if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5111        if (pFormat != NULL) *pFormat = format;
5112        if (pChannels != NULL) *pChannels = reqChannels;
5113
5114        input->stream->common.standby(&input->stream->common);
5115
5116        // notify client processes of the new input creation
5117        thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5118        return id;
5119    }
5120
5121    return 0;
5122}
5123
5124status_t AudioFlinger::closeInput(audio_io_handle_t input)
5125{
5126    // keep strong reference on the record thread so that
5127    // it is not destroyed while exit() is executed
5128    sp <RecordThread> thread;
5129    {
5130        Mutex::Autolock _l(mLock);
5131        thread = checkRecordThread_l(input);
5132        if (thread == NULL) {
5133            return BAD_VALUE;
5134        }
5135
5136        ALOGV("closeInput() %d", input);
5137        void *param2 = NULL;
5138        audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5139        mRecordThreads.removeItem(input);
5140    }
5141    thread->exit();
5142    // The thread entity (active unit of execution) is no longer running here,
5143    // but the ThreadBase container still exists.
5144
5145    AudioStreamIn *in = thread->clearInput();
5146    assert(in != NULL);
5147    // from now on thread->mInput is NULL
5148    in->hwDev->close_input_stream(in->hwDev, in->stream);
5149    delete in;
5150
5151    return NO_ERROR;
5152}
5153
5154status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
5155{
5156    Mutex::Autolock _l(mLock);
5157    MixerThread *dstThread = checkMixerThread_l(output);
5158    if (dstThread == NULL) {
5159        ALOGW("setStreamOutput() bad output id %d", output);
5160        return BAD_VALUE;
5161    }
5162
5163    ALOGV("setStreamOutput() stream %d to output %d", stream, output);
5164    audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5165
5166    dstThread->setStreamValid(stream, true);
5167
5168    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5169        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5170        if (thread != dstThread &&
5171            thread->type() != ThreadBase::DIRECT) {
5172            MixerThread *srcThread = (MixerThread *)thread;
5173            srcThread->setStreamValid(stream, false);
5174            srcThread->invalidateTracks(stream);
5175        }
5176    }
5177
5178    return NO_ERROR;
5179}
5180
5181
5182int AudioFlinger::newAudioSessionId()
5183{
5184    return nextUniqueId();
5185}
5186
5187void AudioFlinger::acquireAudioSessionId(int audioSession)
5188{
5189    Mutex::Autolock _l(mLock);
5190    pid_t caller = IPCThreadState::self()->getCallingPid();
5191    ALOGV("acquiring %d from %d", audioSession, caller);
5192    int num = mAudioSessionRefs.size();
5193    for (int i = 0; i< num; i++) {
5194        AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5195        if (ref->sessionid == audioSession && ref->pid == caller) {
5196            ref->cnt++;
5197            ALOGV(" incremented refcount to %d", ref->cnt);
5198            return;
5199        }
5200    }
5201    mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5202    ALOGV(" added new entry for %d", audioSession);
5203}
5204
5205void AudioFlinger::releaseAudioSessionId(int audioSession)
5206{
5207    Mutex::Autolock _l(mLock);
5208    pid_t caller = IPCThreadState::self()->getCallingPid();
5209    ALOGV("releasing %d from %d", audioSession, caller);
5210    int num = mAudioSessionRefs.size();
5211    for (int i = 0; i< num; i++) {
5212        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5213        if (ref->sessionid == audioSession && ref->pid == caller) {
5214            ref->cnt--;
5215            ALOGV(" decremented refcount to %d", ref->cnt);
5216            if (ref->cnt == 0) {
5217                mAudioSessionRefs.removeAt(i);
5218                delete ref;
5219                purgeStaleEffects_l();
5220            }
5221            return;
5222        }
5223    }
5224    ALOGW("session id %d not found for pid %d", audioSession, caller);
5225}
5226
5227void AudioFlinger::purgeStaleEffects_l() {
5228
5229    ALOGV("purging stale effects");
5230
5231    Vector< sp<EffectChain> > chains;
5232
5233    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5234        sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5235        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5236            sp<EffectChain> ec = t->mEffectChains[j];
5237            if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5238                chains.push(ec);
5239            }
5240        }
5241    }
5242    for (size_t i = 0; i < mRecordThreads.size(); i++) {
5243        sp<RecordThread> t = mRecordThreads.valueAt(i);
5244        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5245            sp<EffectChain> ec = t->mEffectChains[j];
5246            chains.push(ec);
5247        }
5248    }
5249
5250    for (size_t i = 0; i < chains.size(); i++) {
5251        sp<EffectChain> ec = chains[i];
5252        int sessionid = ec->sessionId();
5253        sp<ThreadBase> t = ec->mThread.promote();
5254        if (t == 0) {
5255            continue;
5256        }
5257        size_t numsessionrefs = mAudioSessionRefs.size();
5258        bool found = false;
5259        for (size_t k = 0; k < numsessionrefs; k++) {
5260            AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5261            if (ref->sessionid == sessionid) {
5262                ALOGV(" session %d still exists for %d with %d refs",
5263                     sessionid, ref->pid, ref->cnt);
5264                found = true;
5265                break;
5266            }
5267        }
5268        if (!found) {
5269            // remove all effects from the chain
5270            while (ec->mEffects.size()) {
5271                sp<EffectModule> effect = ec->mEffects[0];
5272                effect->unPin();
5273                Mutex::Autolock _l (t->mLock);
5274                t->removeEffect_l(effect);
5275                for (size_t j = 0; j < effect->mHandles.size(); j++) {
5276                    sp<EffectHandle> handle = effect->mHandles[j].promote();
5277                    if (handle != 0) {
5278                        handle->mEffect.clear();
5279                        if (handle->mHasControl && handle->mEnabled) {
5280                            t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5281                        }
5282                    }
5283                }
5284                AudioSystem::unregisterEffect(effect->id());
5285            }
5286        }
5287    }
5288    return;
5289}
5290
5291// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5292AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
5293{
5294    PlaybackThread *thread = NULL;
5295    if (mPlaybackThreads.indexOfKey(output) >= 0) {
5296        thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5297    }
5298    return thread;
5299}
5300
5301// checkMixerThread_l() must be called with AudioFlinger::mLock held
5302AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
5303{
5304    PlaybackThread *thread = checkPlaybackThread_l(output);
5305    if (thread != NULL) {
5306        if (thread->type() == ThreadBase::DIRECT) {
5307            thread = NULL;
5308        }
5309    }
5310    return (MixerThread *)thread;
5311}
5312
5313// checkRecordThread_l() must be called with AudioFlinger::mLock held
5314AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
5315{
5316    RecordThread *thread = NULL;
5317    if (mRecordThreads.indexOfKey(input) >= 0) {
5318        thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5319    }
5320    return thread;
5321}
5322
5323uint32_t AudioFlinger::nextUniqueId()
5324{
5325    return android_atomic_inc(&mNextUniqueId);
5326}
5327
5328AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5329{
5330    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5331        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5332        AudioStreamOut *output = thread->getOutput();
5333        if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
5334            return thread;
5335        }
5336    }
5337    return NULL;
5338}
5339
5340uint32_t AudioFlinger::primaryOutputDevice_l()
5341{
5342    PlaybackThread *thread = primaryPlaybackThread_l();
5343
5344    if (thread == NULL) {
5345        return 0;
5346    }
5347
5348    return thread->device();
5349}
5350
5351
5352// ----------------------------------------------------------------------------
5353//  Effect management
5354// ----------------------------------------------------------------------------
5355
5356
5357status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
5358{
5359    Mutex::Autolock _l(mLock);
5360    return EffectQueryNumberEffects(numEffects);
5361}
5362
5363status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
5364{
5365    Mutex::Autolock _l(mLock);
5366    return EffectQueryEffect(index, descriptor);
5367}
5368
5369status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
5370        effect_descriptor_t *descriptor) const
5371{
5372    Mutex::Autolock _l(mLock);
5373    return EffectGetDescriptor(pUuid, descriptor);
5374}
5375
5376
5377sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5378        effect_descriptor_t *pDesc,
5379        const sp<IEffectClient>& effectClient,
5380        int32_t priority,
5381        audio_io_handle_t io,
5382        int sessionId,
5383        status_t *status,
5384        int *id,
5385        int *enabled)
5386{
5387    status_t lStatus = NO_ERROR;
5388    sp<EffectHandle> handle;
5389    effect_descriptor_t desc;
5390
5391    ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
5392            pid, effectClient.get(), priority, sessionId, io);
5393
5394    if (pDesc == NULL) {
5395        lStatus = BAD_VALUE;
5396        goto Exit;
5397    }
5398
5399    // check audio settings permission for global effects
5400    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
5401        lStatus = PERMISSION_DENIED;
5402        goto Exit;
5403    }
5404
5405    // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
5406    // that can only be created by audio policy manager (running in same process)
5407    if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
5408        lStatus = PERMISSION_DENIED;
5409        goto Exit;
5410    }
5411
5412    if (io == 0) {
5413        if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
5414            // output must be specified by AudioPolicyManager when using session
5415            // AUDIO_SESSION_OUTPUT_STAGE
5416            lStatus = BAD_VALUE;
5417            goto Exit;
5418        } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
5419            // if the output returned by getOutputForEffect() is removed before we lock the
5420            // mutex below, the call to checkPlaybackThread_l(io) below will detect it
5421            // and we will exit safely
5422            io = AudioSystem::getOutputForEffect(&desc);
5423        }
5424    }
5425
5426    {
5427        Mutex::Autolock _l(mLock);
5428
5429
5430        if (!EffectIsNullUuid(&pDesc->uuid)) {
5431            // if uuid is specified, request effect descriptor
5432            lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5433            if (lStatus < 0) {
5434                ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5435                goto Exit;
5436            }
5437        } else {
5438            // if uuid is not specified, look for an available implementation
5439            // of the required type in effect factory
5440            if (EffectIsNullUuid(&pDesc->type)) {
5441                ALOGW("createEffect() no effect type");
5442                lStatus = BAD_VALUE;
5443                goto Exit;
5444            }
5445            uint32_t numEffects = 0;
5446            effect_descriptor_t d;
5447            d.flags = 0; // prevent compiler warning
5448            bool found = false;
5449
5450            lStatus = EffectQueryNumberEffects(&numEffects);
5451            if (lStatus < 0) {
5452                ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5453                goto Exit;
5454            }
5455            for (uint32_t i = 0; i < numEffects; i++) {
5456                lStatus = EffectQueryEffect(i, &desc);
5457                if (lStatus < 0) {
5458                    ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5459                    continue;
5460                }
5461                if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5462                    // If matching type found save effect descriptor. If the session is
5463                    // 0 and the effect is not auxiliary, continue enumeration in case
5464                    // an auxiliary version of this effect type is available
5465                    found = true;
5466                    memcpy(&d, &desc, sizeof(effect_descriptor_t));
5467                    if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
5468                            (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5469                        break;
5470                    }
5471                }
5472            }
5473            if (!found) {
5474                lStatus = BAD_VALUE;
5475                ALOGW("createEffect() effect not found");
5476                goto Exit;
5477            }
5478            // For same effect type, chose auxiliary version over insert version if
5479            // connect to output mix (Compliance to OpenSL ES)
5480            if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
5481                    (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5482                memcpy(&desc, &d, sizeof(effect_descriptor_t));
5483            }
5484        }
5485
5486        // Do not allow auxiliary effects on a session different from 0 (output mix)
5487        if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
5488             (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5489            lStatus = INVALID_OPERATION;
5490            goto Exit;
5491        }
5492
5493        // check recording permission for visualizer
5494        if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5495            !recordingAllowed()) {
5496            lStatus = PERMISSION_DENIED;
5497            goto Exit;
5498        }
5499
5500        // return effect descriptor
5501        memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5502
5503        // If output is not specified try to find a matching audio session ID in one of the
5504        // output threads.
5505        // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5506        // because of code checking output when entering the function.
5507        // Note: io is never 0 when creating an effect on an input
5508        if (io == 0) {
5509             // look for the thread where the specified audio session is present
5510            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5511                if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5512                    io = mPlaybackThreads.keyAt(i);
5513                    break;
5514                }
5515            }
5516            if (io == 0) {
5517               for (size_t i = 0; i < mRecordThreads.size(); i++) {
5518                   if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5519                       io = mRecordThreads.keyAt(i);
5520                       break;
5521                   }
5522               }
5523            }
5524            // If no output thread contains the requested session ID, default to
5525            // first output. The effect chain will be moved to the correct output
5526            // thread when a track with the same session ID is created
5527            if (io == 0 && mPlaybackThreads.size()) {
5528                io = mPlaybackThreads.keyAt(0);
5529            }
5530            ALOGV("createEffect() got io %d for effect %s", io, desc.name);
5531        }
5532        ThreadBase *thread = checkRecordThread_l(io);
5533        if (thread == NULL) {
5534            thread = checkPlaybackThread_l(io);
5535            if (thread == NULL) {
5536                ALOGE("createEffect() unknown output thread");
5537                lStatus = BAD_VALUE;
5538                goto Exit;
5539            }
5540        }
5541
5542        sp<Client> client = registerPid_l(pid);
5543
5544        // create effect on selected output thread
5545        handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5546                &desc, enabled, &lStatus);
5547        if (handle != 0 && id != NULL) {
5548            *id = handle->id();
5549        }
5550    }
5551
5552Exit:
5553    if(status) {
5554        *status = lStatus;
5555    }
5556    return handle;
5557}
5558
5559status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
5560        audio_io_handle_t dstOutput)
5561{
5562    ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
5563            sessionId, srcOutput, dstOutput);
5564    Mutex::Autolock _l(mLock);
5565    if (srcOutput == dstOutput) {
5566        ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
5567        return NO_ERROR;
5568    }
5569    PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5570    if (srcThread == NULL) {
5571        ALOGW("moveEffects() bad srcOutput %d", srcOutput);
5572        return BAD_VALUE;
5573    }
5574    PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5575    if (dstThread == NULL) {
5576        ALOGW("moveEffects() bad dstOutput %d", dstOutput);
5577        return BAD_VALUE;
5578    }
5579
5580    Mutex::Autolock _dl(dstThread->mLock);
5581    Mutex::Autolock _sl(srcThread->mLock);
5582    moveEffectChain_l(sessionId, srcThread, dstThread, false);
5583
5584    return NO_ERROR;
5585}
5586
5587// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
5588status_t AudioFlinger::moveEffectChain_l(int sessionId,
5589                                   AudioFlinger::PlaybackThread *srcThread,
5590                                   AudioFlinger::PlaybackThread *dstThread,
5591                                   bool reRegister)
5592{
5593    ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
5594            sessionId, srcThread, dstThread);
5595
5596    sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
5597    if (chain == 0) {
5598        ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
5599                sessionId, srcThread);
5600        return INVALID_OPERATION;
5601    }
5602
5603    // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
5604    // so that a new chain is created with correct parameters when first effect is added. This is
5605    // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
5606    // removed.
5607    srcThread->removeEffectChain_l(chain);
5608
5609    // transfer all effects one by one so that new effect chain is created on new thread with
5610    // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
5611    audio_io_handle_t dstOutput = dstThread->id();
5612    sp<EffectChain> dstChain;
5613    uint32_t strategy = 0; // prevent compiler warning
5614    sp<EffectModule> effect = chain->getEffectFromId_l(0);
5615    while (effect != 0) {
5616        srcThread->removeEffect_l(effect);
5617        dstThread->addEffect_l(effect);
5618        // removeEffect_l() has stopped the effect if it was active so it must be restarted
5619        if (effect->state() == EffectModule::ACTIVE ||
5620                effect->state() == EffectModule::STOPPING) {
5621            effect->start();
5622        }
5623        // if the move request is not received from audio policy manager, the effect must be
5624        // re-registered with the new strategy and output
5625        if (dstChain == 0) {
5626            dstChain = effect->chain().promote();
5627            if (dstChain == 0) {
5628                ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5629                srcThread->addEffect_l(effect);
5630                return NO_INIT;
5631            }
5632            strategy = dstChain->strategy();
5633        }
5634        if (reRegister) {
5635            AudioSystem::unregisterEffect(effect->id());
5636            AudioSystem::registerEffect(&effect->desc(),
5637                                        dstOutput,
5638                                        strategy,
5639                                        sessionId,
5640                                        effect->id());
5641        }
5642        effect = chain->getEffectFromId_l(0);
5643    }
5644
5645    return NO_ERROR;
5646}
5647
5648
5649// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
5650sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
5651        const sp<AudioFlinger::Client>& client,
5652        const sp<IEffectClient>& effectClient,
5653        int32_t priority,
5654        int sessionId,
5655        effect_descriptor_t *desc,
5656        int *enabled,
5657        status_t *status
5658        )
5659{
5660    sp<EffectModule> effect;
5661    sp<EffectHandle> handle;
5662    status_t lStatus;
5663    sp<EffectChain> chain;
5664    bool chainCreated = false;
5665    bool effectCreated = false;
5666    bool effectRegistered = false;
5667
5668    lStatus = initCheck();
5669    if (lStatus != NO_ERROR) {
5670        ALOGW("createEffect_l() Audio driver not initialized.");
5671        goto Exit;
5672    }
5673
5674    // Do not allow effects with session ID 0 on direct output or duplicating threads
5675    // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
5676    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
5677        ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5678                desc->name, sessionId);
5679        lStatus = BAD_VALUE;
5680        goto Exit;
5681    }
5682    // Only Pre processor effects are allowed on input threads and only on input threads
5683    if ((mType == RECORD &&
5684            (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5685            (mType != RECORD &&
5686                    (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5687        ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5688                desc->name, desc->flags, mType);
5689        lStatus = BAD_VALUE;
5690        goto Exit;
5691    }
5692
5693    ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
5694
5695    { // scope for mLock
5696        Mutex::Autolock _l(mLock);
5697
5698        // check for existing effect chain with the requested audio session
5699        chain = getEffectChain_l(sessionId);
5700        if (chain == 0) {
5701            // create a new chain for this session
5702            ALOGV("createEffect_l() new effect chain for session %d", sessionId);
5703            chain = new EffectChain(this, sessionId);
5704            addEffectChain_l(chain);
5705            chain->setStrategy(getStrategyForSession_l(sessionId));
5706            chainCreated = true;
5707        } else {
5708            effect = chain->getEffectFromDesc_l(desc);
5709        }
5710
5711        ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
5712
5713        if (effect == 0) {
5714            int id = mAudioFlinger->nextUniqueId();
5715            // Check CPU and memory usage
5716            lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
5717            if (lStatus != NO_ERROR) {
5718                goto Exit;
5719            }
5720            effectRegistered = true;
5721            // create a new effect module if none present in the chain
5722            effect = new EffectModule(this, chain, desc, id, sessionId);
5723            lStatus = effect->status();
5724            if (lStatus != NO_ERROR) {
5725                goto Exit;
5726            }
5727            lStatus = chain->addEffect_l(effect);
5728            if (lStatus != NO_ERROR) {
5729                goto Exit;
5730            }
5731            effectCreated = true;
5732
5733            effect->setDevice(mDevice);
5734            effect->setMode(mAudioFlinger->getMode());
5735        }
5736        // create effect handle and connect it to effect module
5737        handle = new EffectHandle(effect, client, effectClient, priority);
5738        lStatus = effect->addHandle(handle);
5739        if (enabled != NULL) {
5740            *enabled = (int)effect->isEnabled();
5741        }
5742    }
5743
5744Exit:
5745    if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
5746        Mutex::Autolock _l(mLock);
5747        if (effectCreated) {
5748            chain->removeEffect_l(effect);
5749        }
5750        if (effectRegistered) {
5751            AudioSystem::unregisterEffect(effect->id());
5752        }
5753        if (chainCreated) {
5754            removeEffectChain_l(chain);
5755        }
5756        handle.clear();
5757    }
5758
5759    if(status) {
5760        *status = lStatus;
5761    }
5762    return handle;
5763}
5764
5765sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5766{
5767    sp<EffectChain> chain = getEffectChain_l(sessionId);
5768    return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
5769}
5770
5771// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5772// PlaybackThread::mLock held
5773status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
5774{
5775    // check for existing effect chain with the requested audio session
5776    int sessionId = effect->sessionId();
5777    sp<EffectChain> chain = getEffectChain_l(sessionId);
5778    bool chainCreated = false;
5779
5780    if (chain == 0) {
5781        // create a new chain for this session
5782        ALOGV("addEffect_l() new effect chain for session %d", sessionId);
5783        chain = new EffectChain(this, sessionId);
5784        addEffectChain_l(chain);
5785        chain->setStrategy(getStrategyForSession_l(sessionId));
5786        chainCreated = true;
5787    }
5788    ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5789
5790    if (chain->getEffectFromId_l(effect->id()) != 0) {
5791        ALOGW("addEffect_l() %p effect %s already present in chain %p",
5792                this, effect->desc().name, chain.get());
5793        return BAD_VALUE;
5794    }
5795
5796    status_t status = chain->addEffect_l(effect);
5797    if (status != NO_ERROR) {
5798        if (chainCreated) {
5799            removeEffectChain_l(chain);
5800        }
5801        return status;
5802    }
5803
5804    effect->setDevice(mDevice);
5805    effect->setMode(mAudioFlinger->getMode());
5806    return NO_ERROR;
5807}
5808
5809void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
5810
5811    ALOGV("removeEffect_l() %p effect %p", this, effect.get());
5812    effect_descriptor_t desc = effect->desc();
5813    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5814        detachAuxEffect_l(effect->id());
5815    }
5816
5817    sp<EffectChain> chain = effect->chain().promote();
5818    if (chain != 0) {
5819        // remove effect chain if removing last effect
5820        if (chain->removeEffect_l(effect) == 0) {
5821            removeEffectChain_l(chain);
5822        }
5823    } else {
5824        ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5825    }
5826}
5827
5828void AudioFlinger::ThreadBase::lockEffectChains_l(
5829        Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5830{
5831    effectChains = mEffectChains;
5832    for (size_t i = 0; i < mEffectChains.size(); i++) {
5833        mEffectChains[i]->lock();
5834    }
5835}
5836
5837void AudioFlinger::ThreadBase::unlockEffectChains(
5838        Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5839{
5840    for (size_t i = 0; i < effectChains.size(); i++) {
5841        effectChains[i]->unlock();
5842    }
5843}
5844
5845sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5846{
5847    Mutex::Autolock _l(mLock);
5848    return getEffectChain_l(sessionId);
5849}
5850
5851sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5852{
5853    size_t size = mEffectChains.size();
5854    for (size_t i = 0; i < size; i++) {
5855        if (mEffectChains[i]->sessionId() == sessionId) {
5856            return mEffectChains[i];
5857        }
5858    }
5859    return 0;
5860}
5861
5862void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
5863{
5864    Mutex::Autolock _l(mLock);
5865    size_t size = mEffectChains.size();
5866    for (size_t i = 0; i < size; i++) {
5867        mEffectChains[i]->setMode_l(mode);
5868    }
5869}
5870
5871void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
5872                                                    const wp<EffectHandle>& handle,
5873                                                    bool unpinIfLast) {
5874
5875    Mutex::Autolock _l(mLock);
5876    ALOGV("disconnectEffect() %p effect %p", this, effect.get());
5877    // delete the effect module if removing last handle on it
5878    if (effect->removeHandle(handle) == 0) {
5879        if (!effect->isPinned() || unpinIfLast) {
5880            removeEffect_l(effect);
5881            AudioSystem::unregisterEffect(effect->id());
5882        }
5883    }
5884}
5885
5886status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5887{
5888    int session = chain->sessionId();
5889    int16_t *buffer = mMixBuffer;
5890    bool ownsBuffer = false;
5891
5892    ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5893    if (session > 0) {
5894        // Only one effect chain can be present in direct output thread and it uses
5895        // the mix buffer as input
5896        if (mType != DIRECT) {
5897            size_t numSamples = mFrameCount * mChannelCount;
5898            buffer = new int16_t[numSamples];
5899            memset(buffer, 0, numSamples * sizeof(int16_t));
5900            ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5901            ownsBuffer = true;
5902        }
5903
5904        // Attach all tracks with same session ID to this chain.
5905        for (size_t i = 0; i < mTracks.size(); ++i) {
5906            sp<Track> track = mTracks[i];
5907            if (session == track->sessionId()) {
5908                ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5909                track->setMainBuffer(buffer);
5910                chain->incTrackCnt();
5911            }
5912        }
5913
5914        // indicate all active tracks in the chain
5915        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5916            sp<Track> track = mActiveTracks[i].promote();
5917            if (track == 0) continue;
5918            if (session == track->sessionId()) {
5919                ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
5920                chain->incActiveTrackCnt();
5921            }
5922        }
5923    }
5924
5925    chain->setInBuffer(buffer, ownsBuffer);
5926    chain->setOutBuffer(mMixBuffer);
5927    // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
5928    // chains list in order to be processed last as it contains output stage effects
5929    // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5930    // session AUDIO_SESSION_OUTPUT_STAGE to be processed
5931    // after track specific effects and before output stage
5932    // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5933    // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
5934    // Effect chain for other sessions are inserted at beginning of effect
5935    // chains list to be processed before output mix effects. Relative order between other
5936    // sessions is not important
5937    size_t size = mEffectChains.size();
5938    size_t i = 0;
5939    for (i = 0; i < size; i++) {
5940        if (mEffectChains[i]->sessionId() < session) break;
5941    }
5942    mEffectChains.insertAt(chain, i);
5943    checkSuspendOnAddEffectChain_l(chain);
5944
5945    return NO_ERROR;
5946}
5947
5948size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5949{
5950    int session = chain->sessionId();
5951
5952    ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5953
5954    for (size_t i = 0; i < mEffectChains.size(); i++) {
5955        if (chain == mEffectChains[i]) {
5956            mEffectChains.removeAt(i);
5957            // detach all active tracks from the chain
5958            for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5959                sp<Track> track = mActiveTracks[i].promote();
5960                if (track == 0) continue;
5961                if (session == track->sessionId()) {
5962                    ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
5963                            chain.get(), session);
5964                    chain->decActiveTrackCnt();
5965                }
5966            }
5967
5968            // detach all tracks with same session ID from this chain
5969            for (size_t i = 0; i < mTracks.size(); ++i) {
5970                sp<Track> track = mTracks[i];
5971                if (session == track->sessionId()) {
5972                    track->setMainBuffer(mMixBuffer);
5973                    chain->decTrackCnt();
5974                }
5975            }
5976            break;
5977        }
5978    }
5979    return mEffectChains.size();
5980}
5981
5982status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5983        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
5984{
5985    Mutex::Autolock _l(mLock);
5986    return attachAuxEffect_l(track, EffectId);
5987}
5988
5989status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5990        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
5991{
5992    status_t status = NO_ERROR;
5993
5994    if (EffectId == 0) {
5995        track->setAuxBuffer(0, NULL);
5996    } else {
5997        // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5998        sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
5999        if (effect != 0) {
6000            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6001                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6002            } else {
6003                status = INVALID_OPERATION;
6004            }
6005        } else {
6006            status = BAD_VALUE;
6007        }
6008    }
6009    return status;
6010}
6011
6012void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6013{
6014     for (size_t i = 0; i < mTracks.size(); ++i) {
6015        sp<Track> track = mTracks[i];
6016        if (track->auxEffectId() == effectId) {
6017            attachAuxEffect_l(track, 0);
6018        }
6019    }
6020}
6021
6022status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6023{
6024    // only one chain per input thread
6025    if (mEffectChains.size() != 0) {
6026        return INVALID_OPERATION;
6027    }
6028    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6029
6030    chain->setInBuffer(NULL);
6031    chain->setOutBuffer(NULL);
6032
6033    checkSuspendOnAddEffectChain_l(chain);
6034
6035    mEffectChains.add(chain);
6036
6037    return NO_ERROR;
6038}
6039
6040size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6041{
6042    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6043    ALOGW_IF(mEffectChains.size() != 1,
6044            "removeEffectChain_l() %p invalid chain size %d on thread %p",
6045            chain.get(), mEffectChains.size(), this);
6046    if (mEffectChains.size() == 1) {
6047        mEffectChains.removeAt(0);
6048    }
6049    return 0;
6050}
6051
6052// ----------------------------------------------------------------------------
6053//  EffectModule implementation
6054// ----------------------------------------------------------------------------
6055
6056#undef LOG_TAG
6057#define LOG_TAG "AudioFlinger::EffectModule"
6058
6059AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6060                                        const wp<AudioFlinger::EffectChain>& chain,
6061                                        effect_descriptor_t *desc,
6062                                        int id,
6063                                        int sessionId)
6064    : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
6065      mStatus(NO_INIT), mState(IDLE), mSuspended(false)
6066{
6067    ALOGV("Constructor %p", this);
6068    int lStatus;
6069    sp<ThreadBase> thread = mThread.promote();
6070    if (thread == 0) {
6071        return;
6072    }
6073
6074    memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6075
6076    // create effect engine from effect factory
6077    mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
6078
6079    if (mStatus != NO_ERROR) {
6080        return;
6081    }
6082    lStatus = init();
6083    if (lStatus < 0) {
6084        mStatus = lStatus;
6085        goto Error;
6086    }
6087
6088    if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6089        mPinned = true;
6090    }
6091    ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
6092    return;
6093Error:
6094    EffectRelease(mEffectInterface);
6095    mEffectInterface = NULL;
6096    ALOGV("Constructor Error %d", mStatus);
6097}
6098
6099AudioFlinger::EffectModule::~EffectModule()
6100{
6101    ALOGV("Destructor %p", this);
6102    if (mEffectInterface != NULL) {
6103        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6104                (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6105            sp<ThreadBase> thread = mThread.promote();
6106            if (thread != 0) {
6107                audio_stream_t *stream = thread->stream();
6108                if (stream != NULL) {
6109                    stream->remove_audio_effect(stream, mEffectInterface);
6110                }
6111            }
6112        }
6113        // release effect engine
6114        EffectRelease(mEffectInterface);
6115    }
6116}
6117
6118status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
6119{
6120    status_t status;
6121
6122    Mutex::Autolock _l(mLock);
6123    // First handle in mHandles has highest priority and controls the effect module
6124    int priority = handle->priority();
6125    size_t size = mHandles.size();
6126    sp<EffectHandle> h;
6127    size_t i;
6128    for (i = 0; i < size; i++) {
6129        h = mHandles[i].promote();
6130        if (h == 0) continue;
6131        if (h->priority() <= priority) break;
6132    }
6133    // if inserted in first place, move effect control from previous owner to this handle
6134    if (i == 0) {
6135        bool enabled = false;
6136        if (h != 0) {
6137            enabled = h->enabled();
6138            h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
6139        }
6140        handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
6141        status = NO_ERROR;
6142    } else {
6143        status = ALREADY_EXISTS;
6144    }
6145    ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
6146    mHandles.insertAt(handle, i);
6147    return status;
6148}
6149
6150size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6151{
6152    Mutex::Autolock _l(mLock);
6153    size_t size = mHandles.size();
6154    size_t i;
6155    for (i = 0; i < size; i++) {
6156        if (mHandles[i] == handle) break;
6157    }
6158    if (i == size) {
6159        return size;
6160    }
6161    ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
6162
6163    bool enabled = false;
6164    EffectHandle *hdl = handle.unsafe_get();
6165    if (hdl != NULL) {
6166        ALOGV("removeHandle() unsafe_get OK");
6167        enabled = hdl->enabled();
6168    }
6169    mHandles.removeAt(i);
6170    size = mHandles.size();
6171    // if removed from first place, move effect control from this handle to next in line
6172    if (i == 0 && size != 0) {
6173        sp<EffectHandle> h = mHandles[0].promote();
6174        if (h != 0) {
6175            h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
6176        }
6177    }
6178
6179    // Prevent calls to process() and other functions on effect interface from now on.
6180    // The effect engine will be released by the destructor when the last strong reference on
6181    // this object is released which can happen after next process is called.
6182    if (size == 0 && !mPinned) {
6183        mState = DESTROYED;
6184    }
6185
6186    return size;
6187}
6188
6189sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6190{
6191    Mutex::Autolock _l(mLock);
6192    return mHandles.size() != 0 ? mHandles[0].promote() : 0;
6193}
6194
6195void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
6196{
6197    ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
6198    // keep a strong reference on this EffectModule to avoid calling the
6199    // destructor before we exit
6200    sp<EffectModule> keep(this);
6201    {
6202        sp<ThreadBase> thread = mThread.promote();
6203        if (thread != 0) {
6204            thread->disconnectEffect(keep, handle, unpinIfLast);
6205        }
6206    }
6207}
6208
6209void AudioFlinger::EffectModule::updateState() {
6210    Mutex::Autolock _l(mLock);
6211
6212    switch (mState) {
6213    case RESTART:
6214        reset_l();
6215        // FALL THROUGH
6216
6217    case STARTING:
6218        // clear auxiliary effect input buffer for next accumulation
6219        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6220            memset(mConfig.inputCfg.buffer.raw,
6221                   0,
6222                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6223        }
6224        start_l();
6225        mState = ACTIVE;
6226        break;
6227    case STOPPING:
6228        stop_l();
6229        mDisableWaitCnt = mMaxDisableWaitCnt;
6230        mState = STOPPED;
6231        break;
6232    case STOPPED:
6233        // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6234        // turn off sequence.
6235        if (--mDisableWaitCnt == 0) {
6236            reset_l();
6237            mState = IDLE;
6238        }
6239        break;
6240    default: //IDLE , ACTIVE, DESTROYED
6241        break;
6242    }
6243}
6244
6245void AudioFlinger::EffectModule::process()
6246{
6247    Mutex::Autolock _l(mLock);
6248
6249    if (mState == DESTROYED || mEffectInterface == NULL ||
6250            mConfig.inputCfg.buffer.raw == NULL ||
6251            mConfig.outputCfg.buffer.raw == NULL) {
6252        return;
6253    }
6254
6255    if (isProcessEnabled()) {
6256        // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6257        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6258            ditherAndClamp(mConfig.inputCfg.buffer.s32,
6259                                        mConfig.inputCfg.buffer.s32,
6260                                        mConfig.inputCfg.buffer.frameCount/2);
6261        }
6262
6263        // do the actual processing in the effect engine
6264        int ret = (*mEffectInterface)->process(mEffectInterface,
6265                                               &mConfig.inputCfg.buffer,
6266                                               &mConfig.outputCfg.buffer);
6267
6268        // force transition to IDLE state when engine is ready
6269        if (mState == STOPPED && ret == -ENODATA) {
6270            mDisableWaitCnt = 1;
6271        }
6272
6273        // clear auxiliary effect input buffer for next accumulation
6274        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6275            memset(mConfig.inputCfg.buffer.raw, 0,
6276                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6277        }
6278    } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
6279                mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6280        // If an insert effect is idle and input buffer is different from output buffer,
6281        // accumulate input onto output
6282        sp<EffectChain> chain = mChain.promote();
6283        if (chain != 0 && chain->activeTrackCnt() != 0) {
6284            size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2;  //always stereo here
6285            int16_t *in = mConfig.inputCfg.buffer.s16;
6286            int16_t *out = mConfig.outputCfg.buffer.s16;
6287            for (size_t i = 0; i < frameCnt; i++) {
6288                out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
6289            }
6290        }
6291    }
6292}
6293
6294void AudioFlinger::EffectModule::reset_l()
6295{
6296    if (mEffectInterface == NULL) {
6297        return;
6298    }
6299    (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6300}
6301
6302status_t AudioFlinger::EffectModule::configure()
6303{
6304    uint32_t channels;
6305    if (mEffectInterface == NULL) {
6306        return NO_INIT;
6307    }
6308
6309    sp<ThreadBase> thread = mThread.promote();
6310    if (thread == 0) {
6311        return DEAD_OBJECT;
6312    }
6313
6314    // TODO: handle configuration of effects replacing track process
6315    if (thread->channelCount() == 1) {
6316        channels = AUDIO_CHANNEL_OUT_MONO;
6317    } else {
6318        channels = AUDIO_CHANNEL_OUT_STEREO;
6319    }
6320
6321    if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6322        mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
6323    } else {
6324        mConfig.inputCfg.channels = channels;
6325    }
6326    mConfig.outputCfg.channels = channels;
6327    mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6328    mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6329    mConfig.inputCfg.samplingRate = thread->sampleRate();
6330    mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6331    mConfig.inputCfg.bufferProvider.cookie = NULL;
6332    mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6333    mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6334    mConfig.outputCfg.bufferProvider.cookie = NULL;
6335    mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6336    mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6337    mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6338    // Insert effect:
6339    // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
6340    // always overwrites output buffer: input buffer == output buffer
6341    // - in other sessions:
6342    //      last effect in the chain accumulates in output buffer: input buffer != output buffer
6343    //      other effect: overwrites output buffer: input buffer == output buffer
6344    // Auxiliary effect:
6345    //      accumulates in output buffer: input buffer != output buffer
6346    // Therefore: accumulate <=> input buffer != output buffer
6347    if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6348        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6349    } else {
6350        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6351    }
6352    mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6353    mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6354    mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6355    mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6356
6357    ALOGV("configure() %p thread %p buffer %p framecount %d",
6358            this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6359
6360    status_t cmdStatus;
6361    uint32_t size = sizeof(int);
6362    status_t status = (*mEffectInterface)->command(mEffectInterface,
6363                                                   EFFECT_CMD_SET_CONFIG,
6364                                                   sizeof(effect_config_t),
6365                                                   &mConfig,
6366                                                   &size,
6367                                                   &cmdStatus);
6368    if (status == 0) {
6369        status = cmdStatus;
6370    }
6371
6372    mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6373            (1000 * mConfig.outputCfg.buffer.frameCount);
6374
6375    return status;
6376}
6377
6378status_t AudioFlinger::EffectModule::init()
6379{
6380    Mutex::Autolock _l(mLock);
6381    if (mEffectInterface == NULL) {
6382        return NO_INIT;
6383    }
6384    status_t cmdStatus;
6385    uint32_t size = sizeof(status_t);
6386    status_t status = (*mEffectInterface)->command(mEffectInterface,
6387                                                   EFFECT_CMD_INIT,
6388                                                   0,
6389                                                   NULL,
6390                                                   &size,
6391                                                   &cmdStatus);
6392    if (status == 0) {
6393        status = cmdStatus;
6394    }
6395    return status;
6396}
6397
6398status_t AudioFlinger::EffectModule::start()
6399{
6400    Mutex::Autolock _l(mLock);
6401    return start_l();
6402}
6403
6404status_t AudioFlinger::EffectModule::start_l()
6405{
6406    if (mEffectInterface == NULL) {
6407        return NO_INIT;
6408    }
6409    status_t cmdStatus;
6410    uint32_t size = sizeof(status_t);
6411    status_t status = (*mEffectInterface)->command(mEffectInterface,
6412                                                   EFFECT_CMD_ENABLE,
6413                                                   0,
6414                                                   NULL,
6415                                                   &size,
6416                                                   &cmdStatus);
6417    if (status == 0) {
6418        status = cmdStatus;
6419    }
6420    if (status == 0 &&
6421            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6422             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6423        sp<ThreadBase> thread = mThread.promote();
6424        if (thread != 0) {
6425            audio_stream_t *stream = thread->stream();
6426            if (stream != NULL) {
6427                stream->add_audio_effect(stream, mEffectInterface);
6428            }
6429        }
6430    }
6431    return status;
6432}
6433
6434status_t AudioFlinger::EffectModule::stop()
6435{
6436    Mutex::Autolock _l(mLock);
6437    return stop_l();
6438}
6439
6440status_t AudioFlinger::EffectModule::stop_l()
6441{
6442    if (mEffectInterface == NULL) {
6443        return NO_INIT;
6444    }
6445    status_t cmdStatus;
6446    uint32_t size = sizeof(status_t);
6447    status_t status = (*mEffectInterface)->command(mEffectInterface,
6448                                                   EFFECT_CMD_DISABLE,
6449                                                   0,
6450                                                   NULL,
6451                                                   &size,
6452                                                   &cmdStatus);
6453    if (status == 0) {
6454        status = cmdStatus;
6455    }
6456    if (status == 0 &&
6457            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6458             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6459        sp<ThreadBase> thread = mThread.promote();
6460        if (thread != 0) {
6461            audio_stream_t *stream = thread->stream();
6462            if (stream != NULL) {
6463                stream->remove_audio_effect(stream, mEffectInterface);
6464            }
6465        }
6466    }
6467    return status;
6468}
6469
6470status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6471                                             uint32_t cmdSize,
6472                                             void *pCmdData,
6473                                             uint32_t *replySize,
6474                                             void *pReplyData)
6475{
6476    Mutex::Autolock _l(mLock);
6477//    ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
6478
6479    if (mState == DESTROYED || mEffectInterface == NULL) {
6480        return NO_INIT;
6481    }
6482    status_t status = (*mEffectInterface)->command(mEffectInterface,
6483                                                   cmdCode,
6484                                                   cmdSize,
6485                                                   pCmdData,
6486                                                   replySize,
6487                                                   pReplyData);
6488    if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
6489        uint32_t size = (replySize == NULL) ? 0 : *replySize;
6490        for (size_t i = 1; i < mHandles.size(); i++) {
6491            sp<EffectHandle> h = mHandles[i].promote();
6492            if (h != 0) {
6493                h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6494            }
6495        }
6496    }
6497    return status;
6498}
6499
6500status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6501{
6502
6503    Mutex::Autolock _l(mLock);
6504    ALOGV("setEnabled %p enabled %d", this, enabled);
6505
6506    if (enabled != isEnabled()) {
6507        status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6508        if (enabled && status != NO_ERROR) {
6509            return status;
6510        }
6511
6512        switch (mState) {
6513        // going from disabled to enabled
6514        case IDLE:
6515            mState = STARTING;
6516            break;
6517        case STOPPED:
6518            mState = RESTART;
6519            break;
6520        case STOPPING:
6521            mState = ACTIVE;
6522            break;
6523
6524        // going from enabled to disabled
6525        case RESTART:
6526            mState = STOPPED;
6527            break;
6528        case STARTING:
6529            mState = IDLE;
6530            break;
6531        case ACTIVE:
6532            mState = STOPPING;
6533            break;
6534        case DESTROYED:
6535            return NO_ERROR; // simply ignore as we are being destroyed
6536        }
6537        for (size_t i = 1; i < mHandles.size(); i++) {
6538            sp<EffectHandle> h = mHandles[i].promote();
6539            if (h != 0) {
6540                h->setEnabled(enabled);
6541            }
6542        }
6543    }
6544    return NO_ERROR;
6545}
6546
6547bool AudioFlinger::EffectModule::isEnabled() const
6548{
6549    switch (mState) {
6550    case RESTART:
6551    case STARTING:
6552    case ACTIVE:
6553        return true;
6554    case IDLE:
6555    case STOPPING:
6556    case STOPPED:
6557    case DESTROYED:
6558    default:
6559        return false;
6560    }
6561}
6562
6563bool AudioFlinger::EffectModule::isProcessEnabled() const
6564{
6565    switch (mState) {
6566    case RESTART:
6567    case ACTIVE:
6568    case STOPPING:
6569    case STOPPED:
6570        return true;
6571    case IDLE:
6572    case STARTING:
6573    case DESTROYED:
6574    default:
6575        return false;
6576    }
6577}
6578
6579status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6580{
6581    Mutex::Autolock _l(mLock);
6582    status_t status = NO_ERROR;
6583
6584    // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6585    // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
6586    if (isProcessEnabled() &&
6587            ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6588            (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
6589        status_t cmdStatus;
6590        uint32_t volume[2];
6591        uint32_t *pVolume = NULL;
6592        uint32_t size = sizeof(volume);
6593        volume[0] = *left;
6594        volume[1] = *right;
6595        if (controller) {
6596            pVolume = volume;
6597        }
6598        status = (*mEffectInterface)->command(mEffectInterface,
6599                                              EFFECT_CMD_SET_VOLUME,
6600                                              size,
6601                                              volume,
6602                                              &size,
6603                                              pVolume);
6604        if (controller && status == NO_ERROR && size == sizeof(volume)) {
6605            *left = volume[0];
6606            *right = volume[1];
6607        }
6608    }
6609    return status;
6610}
6611
6612status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6613{
6614    Mutex::Autolock _l(mLock);
6615    status_t status = NO_ERROR;
6616    if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6617        // audio pre processing modules on RecordThread can receive both output and
6618        // input device indication in the same call
6619        uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6620        if (dev) {
6621            status_t cmdStatus;
6622            uint32_t size = sizeof(status_t);
6623
6624            status = (*mEffectInterface)->command(mEffectInterface,
6625                                                  EFFECT_CMD_SET_DEVICE,
6626                                                  sizeof(uint32_t),
6627                                                  &dev,
6628                                                  &size,
6629                                                  &cmdStatus);
6630            if (status == NO_ERROR) {
6631                status = cmdStatus;
6632            }
6633        }
6634        dev = device & AUDIO_DEVICE_IN_ALL;
6635        if (dev) {
6636            status_t cmdStatus;
6637            uint32_t size = sizeof(status_t);
6638
6639            status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6640                                                  EFFECT_CMD_SET_INPUT_DEVICE,
6641                                                  sizeof(uint32_t),
6642                                                  &dev,
6643                                                  &size,
6644                                                  &cmdStatus);
6645            if (status2 == NO_ERROR) {
6646                status2 = cmdStatus;
6647            }
6648            if (status == NO_ERROR) {
6649                status = status2;
6650            }
6651        }
6652    }
6653    return status;
6654}
6655
6656status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
6657{
6658    Mutex::Autolock _l(mLock);
6659    status_t status = NO_ERROR;
6660    if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
6661        status_t cmdStatus;
6662        uint32_t size = sizeof(status_t);
6663        status = (*mEffectInterface)->command(mEffectInterface,
6664                                              EFFECT_CMD_SET_AUDIO_MODE,
6665                                              sizeof(audio_mode_t),
6666                                              &mode,
6667                                              &size,
6668                                              &cmdStatus);
6669        if (status == NO_ERROR) {
6670            status = cmdStatus;
6671        }
6672    }
6673    return status;
6674}
6675
6676void AudioFlinger::EffectModule::setSuspended(bool suspended)
6677{
6678    Mutex::Autolock _l(mLock);
6679    mSuspended = suspended;
6680}
6681
6682bool AudioFlinger::EffectModule::suspended() const
6683{
6684    Mutex::Autolock _l(mLock);
6685    return mSuspended;
6686}
6687
6688status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6689{
6690    const size_t SIZE = 256;
6691    char buffer[SIZE];
6692    String8 result;
6693
6694    snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6695    result.append(buffer);
6696
6697    bool locked = tryLock(mLock);
6698    // failed to lock - AudioFlinger is probably deadlocked
6699    if (!locked) {
6700        result.append("\t\tCould not lock Fx mutex:\n");
6701    }
6702
6703    result.append("\t\tSession Status State Engine:\n");
6704    snprintf(buffer, SIZE, "\t\t%05d   %03d    %03d   0x%08x\n",
6705            mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6706    result.append(buffer);
6707
6708    result.append("\t\tDescriptor:\n");
6709    snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6710            mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6711            mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6712            mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6713    result.append(buffer);
6714    snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6715                mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6716                mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6717                mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6718    result.append(buffer);
6719    snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
6720            mDescriptor.apiVersion,
6721            mDescriptor.flags);
6722    result.append(buffer);
6723    snprintf(buffer, SIZE, "\t\t- name: %s\n",
6724            mDescriptor.name);
6725    result.append(buffer);
6726    snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6727            mDescriptor.implementor);
6728    result.append(buffer);
6729
6730    result.append("\t\t- Input configuration:\n");
6731    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
6732    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
6733            (uint32_t)mConfig.inputCfg.buffer.raw,
6734            mConfig.inputCfg.buffer.frameCount,
6735            mConfig.inputCfg.samplingRate,
6736            mConfig.inputCfg.channels,
6737            mConfig.inputCfg.format);
6738    result.append(buffer);
6739
6740    result.append("\t\t- Output configuration:\n");
6741    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
6742    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
6743            (uint32_t)mConfig.outputCfg.buffer.raw,
6744            mConfig.outputCfg.buffer.frameCount,
6745            mConfig.outputCfg.samplingRate,
6746            mConfig.outputCfg.channels,
6747            mConfig.outputCfg.format);
6748    result.append(buffer);
6749
6750    snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6751    result.append(buffer);
6752    result.append("\t\t\tPid   Priority Ctrl Locked client server\n");
6753    for (size_t i = 0; i < mHandles.size(); ++i) {
6754        sp<EffectHandle> handle = mHandles[i].promote();
6755        if (handle != 0) {
6756            handle->dump(buffer, SIZE);
6757            result.append(buffer);
6758        }
6759    }
6760
6761    result.append("\n");
6762
6763    write(fd, result.string(), result.length());
6764
6765    if (locked) {
6766        mLock.unlock();
6767    }
6768
6769    return NO_ERROR;
6770}
6771
6772// ----------------------------------------------------------------------------
6773//  EffectHandle implementation
6774// ----------------------------------------------------------------------------
6775
6776#undef LOG_TAG
6777#define LOG_TAG "AudioFlinger::EffectHandle"
6778
6779AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6780                                        const sp<AudioFlinger::Client>& client,
6781                                        const sp<IEffectClient>& effectClient,
6782                                        int32_t priority)
6783    : BnEffect(),
6784    mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
6785    mPriority(priority), mHasControl(false), mEnabled(false)
6786{
6787    ALOGV("constructor %p", this);
6788
6789    if (client == 0) {
6790        return;
6791    }
6792    int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6793    mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6794    if (mCblkMemory != 0) {
6795        mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6796
6797        if (mCblk != NULL) {
6798            new(mCblk) effect_param_cblk_t();
6799            mBuffer = (uint8_t *)mCblk + bufOffset;
6800         }
6801    } else {
6802        ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6803        return;
6804    }
6805}
6806
6807AudioFlinger::EffectHandle::~EffectHandle()
6808{
6809    ALOGV("Destructor %p", this);
6810    disconnect(false);
6811    ALOGV("Destructor DONE %p", this);
6812}
6813
6814status_t AudioFlinger::EffectHandle::enable()
6815{
6816    ALOGV("enable %p", this);
6817    if (!mHasControl) return INVALID_OPERATION;
6818    if (mEffect == 0) return DEAD_OBJECT;
6819
6820    if (mEnabled) {
6821        return NO_ERROR;
6822    }
6823
6824    mEnabled = true;
6825
6826    sp<ThreadBase> thread = mEffect->thread().promote();
6827    if (thread != 0) {
6828        thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6829    }
6830
6831    // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6832    if (mEffect->suspended()) {
6833        return NO_ERROR;
6834    }
6835
6836    status_t status = mEffect->setEnabled(true);
6837    if (status != NO_ERROR) {
6838        if (thread != 0) {
6839            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6840        }
6841        mEnabled = false;
6842    }
6843    return status;
6844}
6845
6846status_t AudioFlinger::EffectHandle::disable()
6847{
6848    ALOGV("disable %p", this);
6849    if (!mHasControl) return INVALID_OPERATION;
6850    if (mEffect == 0) return DEAD_OBJECT;
6851
6852    if (!mEnabled) {
6853        return NO_ERROR;
6854    }
6855    mEnabled = false;
6856
6857    if (mEffect->suspended()) {
6858        return NO_ERROR;
6859    }
6860
6861    status_t status = mEffect->setEnabled(false);
6862
6863    sp<ThreadBase> thread = mEffect->thread().promote();
6864    if (thread != 0) {
6865        thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6866    }
6867
6868    return status;
6869}
6870
6871void AudioFlinger::EffectHandle::disconnect()
6872{
6873    disconnect(true);
6874}
6875
6876void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
6877{
6878    ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
6879    if (mEffect == 0) {
6880        return;
6881    }
6882    mEffect->disconnect(this, unpinIfLast);
6883
6884    if (mHasControl && mEnabled) {
6885        sp<ThreadBase> thread = mEffect->thread().promote();
6886        if (thread != 0) {
6887            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6888        }
6889    }
6890
6891    // release sp on module => module destructor can be called now
6892    mEffect.clear();
6893    if (mClient != 0) {
6894        if (mCblk != NULL) {
6895            // unlike ~TrackBase(), mCblk is never a local new, so don't delete
6896            mCblk->~effect_param_cblk_t();   // destroy our shared-structure.
6897        }
6898        mCblkMemory.clear();    // free the shared memory before releasing the heap it belongs to
6899        // Client destructor must run with AudioFlinger mutex locked
6900        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6901        mClient.clear();
6902    }
6903}
6904
6905status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6906                                             uint32_t cmdSize,
6907                                             void *pCmdData,
6908                                             uint32_t *replySize,
6909                                             void *pReplyData)
6910{
6911//    ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6912//              cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
6913
6914    // only get parameter command is permitted for applications not controlling the effect
6915    if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6916        return INVALID_OPERATION;
6917    }
6918    if (mEffect == 0) return DEAD_OBJECT;
6919    if (mClient == 0) return INVALID_OPERATION;
6920
6921    // handle commands that are not forwarded transparently to effect engine
6922    if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6923        // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6924        // no risk to block the whole media server process or mixer threads is we are stuck here
6925        Mutex::Autolock _l(mCblk->lock);
6926        if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6927            mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6928            mCblk->serverIndex = 0;
6929            mCblk->clientIndex = 0;
6930            return BAD_VALUE;
6931        }
6932        status_t status = NO_ERROR;
6933        while (mCblk->serverIndex < mCblk->clientIndex) {
6934            int reply;
6935            uint32_t rsize = sizeof(int);
6936            int *p = (int *)(mBuffer + mCblk->serverIndex);
6937            int size = *p++;
6938            if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6939                ALOGW("command(): invalid parameter block size");
6940                break;
6941            }
6942            effect_param_t *param = (effect_param_t *)p;
6943            if (param->psize == 0 || param->vsize == 0) {
6944                ALOGW("command(): null parameter or value size");
6945                mCblk->serverIndex += size;
6946                continue;
6947            }
6948            uint32_t psize = sizeof(effect_param_t) +
6949                             ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6950                             param->vsize;
6951            status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6952                                            psize,
6953                                            p,
6954                                            &rsize,
6955                                            &reply);
6956            // stop at first error encountered
6957            if (ret != NO_ERROR) {
6958                status = ret;
6959                *(int *)pReplyData = reply;
6960                break;
6961            } else if (reply != NO_ERROR) {
6962                *(int *)pReplyData = reply;
6963                break;
6964            }
6965            mCblk->serverIndex += size;
6966        }
6967        mCblk->serverIndex = 0;
6968        mCblk->clientIndex = 0;
6969        return status;
6970    } else if (cmdCode == EFFECT_CMD_ENABLE) {
6971        *(int *)pReplyData = NO_ERROR;
6972        return enable();
6973    } else if (cmdCode == EFFECT_CMD_DISABLE) {
6974        *(int *)pReplyData = NO_ERROR;
6975        return disable();
6976    }
6977
6978    return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6979}
6980
6981void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
6982{
6983    ALOGV("setControl %p control %d", this, hasControl);
6984
6985    mHasControl = hasControl;
6986    mEnabled = enabled;
6987
6988    if (signal && mEffectClient != 0) {
6989        mEffectClient->controlStatusChanged(hasControl);
6990    }
6991}
6992
6993void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6994                                                 uint32_t cmdSize,
6995                                                 void *pCmdData,
6996                                                 uint32_t replySize,
6997                                                 void *pReplyData)
6998{
6999    if (mEffectClient != 0) {
7000        mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7001    }
7002}
7003
7004
7005
7006void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7007{
7008    if (mEffectClient != 0) {
7009        mEffectClient->enableStatusChanged(enabled);
7010    }
7011}
7012
7013status_t AudioFlinger::EffectHandle::onTransact(
7014    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7015{
7016    return BnEffect::onTransact(code, data, reply, flags);
7017}
7018
7019
7020void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7021{
7022    bool locked = mCblk != NULL && tryLock(mCblk->lock);
7023
7024    snprintf(buffer, size, "\t\t\t%05d %05d    %01u    %01u      %05u  %05u\n",
7025            (mClient == 0) ? getpid() : mClient->pid(),
7026            mPriority,
7027            mHasControl,
7028            !locked,
7029            mCblk ? mCblk->clientIndex : 0,
7030            mCblk ? mCblk->serverIndex : 0
7031            );
7032
7033    if (locked) {
7034        mCblk->lock.unlock();
7035    }
7036}
7037
7038#undef LOG_TAG
7039#define LOG_TAG "AudioFlinger::EffectChain"
7040
7041AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7042                                        int sessionId)
7043    : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
7044      mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7045      mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
7046{
7047    mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
7048    sp<ThreadBase> thread = mThread.promote();
7049    if (thread == 0) {
7050        return;
7051    }
7052    mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7053                                    thread->frameCount();
7054}
7055
7056AudioFlinger::EffectChain::~EffectChain()
7057{
7058    if (mOwnInBuffer) {
7059        delete mInBuffer;
7060    }
7061
7062}
7063
7064// getEffectFromDesc_l() must be called with ThreadBase::mLock held
7065sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
7066{
7067    size_t size = mEffects.size();
7068
7069    for (size_t i = 0; i < size; i++) {
7070        if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7071            return mEffects[i];
7072        }
7073    }
7074    return 0;
7075}
7076
7077// getEffectFromId_l() must be called with ThreadBase::mLock held
7078sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
7079{
7080    size_t size = mEffects.size();
7081
7082    for (size_t i = 0; i < size; i++) {
7083        // by convention, return first effect if id provided is 0 (0 is never a valid id)
7084        if (id == 0 || mEffects[i]->id() == id) {
7085            return mEffects[i];
7086        }
7087    }
7088    return 0;
7089}
7090
7091// getEffectFromType_l() must be called with ThreadBase::mLock held
7092sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7093        const effect_uuid_t *type)
7094{
7095    size_t size = mEffects.size();
7096
7097    for (size_t i = 0; i < size; i++) {
7098        if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7099            return mEffects[i];
7100        }
7101    }
7102    return 0;
7103}
7104
7105// Must be called with EffectChain::mLock locked
7106void AudioFlinger::EffectChain::process_l()
7107{
7108    sp<ThreadBase> thread = mThread.promote();
7109    if (thread == 0) {
7110        ALOGW("process_l(): cannot promote mixer thread");
7111        return;
7112    }
7113    bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7114            (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
7115    // always process effects unless no more tracks are on the session and the effect tail
7116    // has been rendered
7117    bool doProcess = true;
7118    if (!isGlobalSession) {
7119        bool tracksOnSession = (trackCnt() != 0);
7120
7121        if (!tracksOnSession && mTailBufferCount == 0) {
7122            doProcess = false;
7123        }
7124
7125        if (activeTrackCnt() == 0) {
7126            // if no track is active and the effect tail has not been rendered,
7127            // the input buffer must be cleared here as the mixer process will not do it
7128            if (tracksOnSession || mTailBufferCount > 0) {
7129                size_t numSamples = thread->frameCount() * thread->channelCount();
7130                memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7131                if (mTailBufferCount > 0) {
7132                    mTailBufferCount--;
7133                }
7134            }
7135        }
7136    }
7137
7138    size_t size = mEffects.size();
7139    if (doProcess) {
7140        for (size_t i = 0; i < size; i++) {
7141            mEffects[i]->process();
7142        }
7143    }
7144    for (size_t i = 0; i < size; i++) {
7145        mEffects[i]->updateState();
7146    }
7147}
7148
7149// addEffect_l() must be called with PlaybackThread::mLock held
7150status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
7151{
7152    effect_descriptor_t desc = effect->desc();
7153    uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7154
7155    Mutex::Autolock _l(mLock);
7156    effect->setChain(this);
7157    sp<ThreadBase> thread = mThread.promote();
7158    if (thread == 0) {
7159        return NO_INIT;
7160    }
7161    effect->setThread(thread);
7162
7163    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7164        // Auxiliary effects are inserted at the beginning of mEffects vector as
7165        // they are processed first and accumulated in chain input buffer
7166        mEffects.insertAt(effect, 0);
7167
7168        // the input buffer for auxiliary effect contains mono samples in
7169        // 32 bit format. This is to avoid saturation in AudoMixer
7170        // accumulation stage. Saturation is done in EffectModule::process() before
7171        // calling the process in effect engine
7172        size_t numSamples = thread->frameCount();
7173        int32_t *buffer = new int32_t[numSamples];
7174        memset(buffer, 0, numSamples * sizeof(int32_t));
7175        effect->setInBuffer((int16_t *)buffer);
7176        // auxiliary effects output samples to chain input buffer for further processing
7177        // by insert effects
7178        effect->setOutBuffer(mInBuffer);
7179    } else {
7180        // Insert effects are inserted at the end of mEffects vector as they are processed
7181        //  after track and auxiliary effects.
7182        // Insert effect order as a function of indicated preference:
7183        //  if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7184        //  another effect is present
7185        //  else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7186        //  last effect claiming first position
7187        //  else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7188        //  first effect claiming last position
7189        //  else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7190        // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7191        // already present
7192
7193        int size = (int)mEffects.size();
7194        int idx_insert = size;
7195        int idx_insert_first = -1;
7196        int idx_insert_last = -1;
7197
7198        for (int i = 0; i < size; i++) {
7199            effect_descriptor_t d = mEffects[i]->desc();
7200            uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7201            uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7202            if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7203                // check invalid effect chaining combinations
7204                if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7205                    iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
7206                    ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
7207                    return INVALID_OPERATION;
7208                }
7209                // remember position of first insert effect and by default
7210                // select this as insert position for new effect
7211                if (idx_insert == size) {
7212                    idx_insert = i;
7213                }
7214                // remember position of last insert effect claiming
7215                // first position
7216                if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7217                    idx_insert_first = i;
7218                }
7219                // remember position of first insert effect claiming
7220                // last position
7221                if (iPref == EFFECT_FLAG_INSERT_LAST &&
7222                    idx_insert_last == -1) {
7223                    idx_insert_last = i;
7224                }
7225            }
7226        }
7227
7228        // modify idx_insert from first position if needed
7229        if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7230            if (idx_insert_last != -1) {
7231                idx_insert = idx_insert_last;
7232            } else {
7233                idx_insert = size;
7234            }
7235        } else {
7236            if (idx_insert_first != -1) {
7237                idx_insert = idx_insert_first + 1;
7238            }
7239        }
7240
7241        // always read samples from chain input buffer
7242        effect->setInBuffer(mInBuffer);
7243
7244        // if last effect in the chain, output samples to chain
7245        // output buffer, otherwise to chain input buffer
7246        if (idx_insert == size) {
7247            if (idx_insert != 0) {
7248                mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7249                mEffects[idx_insert-1]->configure();
7250            }
7251            effect->setOutBuffer(mOutBuffer);
7252        } else {
7253            effect->setOutBuffer(mInBuffer);
7254        }
7255        mEffects.insertAt(effect, idx_insert);
7256
7257        ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
7258    }
7259    effect->configure();
7260    return NO_ERROR;
7261}
7262
7263// removeEffect_l() must be called with PlaybackThread::mLock held
7264size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
7265{
7266    Mutex::Autolock _l(mLock);
7267    int size = (int)mEffects.size();
7268    int i;
7269    uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7270
7271    for (i = 0; i < size; i++) {
7272        if (effect == mEffects[i]) {
7273            // calling stop here will remove pre-processing effect from the audio HAL.
7274            // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7275            // the middle of a read from audio HAL
7276            if (mEffects[i]->state() == EffectModule::ACTIVE ||
7277                    mEffects[i]->state() == EffectModule::STOPPING) {
7278                mEffects[i]->stop();
7279            }
7280            if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7281                delete[] effect->inBuffer();
7282            } else {
7283                if (i == size - 1 && i != 0) {
7284                    mEffects[i - 1]->setOutBuffer(mOutBuffer);
7285                    mEffects[i - 1]->configure();
7286                }
7287            }
7288            mEffects.removeAt(i);
7289            ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
7290            break;
7291        }
7292    }
7293
7294    return mEffects.size();
7295}
7296
7297// setDevice_l() must be called with PlaybackThread::mLock held
7298void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
7299{
7300    size_t size = mEffects.size();
7301    for (size_t i = 0; i < size; i++) {
7302        mEffects[i]->setDevice(device);
7303    }
7304}
7305
7306// setMode_l() must be called with PlaybackThread::mLock held
7307void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
7308{
7309    size_t size = mEffects.size();
7310    for (size_t i = 0; i < size; i++) {
7311        mEffects[i]->setMode(mode);
7312    }
7313}
7314
7315// setVolume_l() must be called with PlaybackThread::mLock held
7316bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
7317{
7318    uint32_t newLeft = *left;
7319    uint32_t newRight = *right;
7320    bool hasControl = false;
7321    int ctrlIdx = -1;
7322    size_t size = mEffects.size();
7323
7324    // first update volume controller
7325    for (size_t i = size; i > 0; i--) {
7326        if (mEffects[i - 1]->isProcessEnabled() &&
7327            (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7328            ctrlIdx = i - 1;
7329            hasControl = true;
7330            break;
7331        }
7332    }
7333
7334    if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
7335        if (hasControl) {
7336            *left = mNewLeftVolume;
7337            *right = mNewRightVolume;
7338        }
7339        return hasControl;
7340    }
7341
7342    mVolumeCtrlIdx = ctrlIdx;
7343    mLeftVolume = newLeft;
7344    mRightVolume = newRight;
7345
7346    // second get volume update from volume controller
7347    if (ctrlIdx >= 0) {
7348        mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
7349        mNewLeftVolume = newLeft;
7350        mNewRightVolume = newRight;
7351    }
7352    // then indicate volume to all other effects in chain.
7353    // Pass altered volume to effects before volume controller
7354    // and requested volume to effects after controller
7355    uint32_t lVol = newLeft;
7356    uint32_t rVol = newRight;
7357
7358    for (size_t i = 0; i < size; i++) {
7359        if ((int)i == ctrlIdx) continue;
7360        // this also works for ctrlIdx == -1 when there is no volume controller
7361        if ((int)i > ctrlIdx) {
7362            lVol = *left;
7363            rVol = *right;
7364        }
7365        mEffects[i]->setVolume(&lVol, &rVol, false);
7366    }
7367    *left = newLeft;
7368    *right = newRight;
7369
7370    return hasControl;
7371}
7372
7373status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7374{
7375    const size_t SIZE = 256;
7376    char buffer[SIZE];
7377    String8 result;
7378
7379    snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7380    result.append(buffer);
7381
7382    bool locked = tryLock(mLock);
7383    // failed to lock - AudioFlinger is probably deadlocked
7384    if (!locked) {
7385        result.append("\tCould not lock mutex:\n");
7386    }
7387
7388    result.append("\tNum fx In buffer   Out buffer   Active tracks:\n");
7389    snprintf(buffer, SIZE, "\t%02d     0x%08x  0x%08x   %d\n",
7390            mEffects.size(),
7391            (uint32_t)mInBuffer,
7392            (uint32_t)mOutBuffer,
7393            mActiveTrackCnt);
7394    result.append(buffer);
7395    write(fd, result.string(), result.size());
7396
7397    for (size_t i = 0; i < mEffects.size(); ++i) {
7398        sp<EffectModule> effect = mEffects[i];
7399        if (effect != 0) {
7400            effect->dump(fd, args);
7401        }
7402    }
7403
7404    if (locked) {
7405        mLock.unlock();
7406    }
7407
7408    return NO_ERROR;
7409}
7410
7411// must be called with ThreadBase::mLock held
7412void AudioFlinger::EffectChain::setEffectSuspended_l(
7413        const effect_uuid_t *type, bool suspend)
7414{
7415    sp<SuspendedEffectDesc> desc;
7416    // use effect type UUID timelow as key as there is no real risk of identical
7417    // timeLow fields among effect type UUIDs.
7418    int index = mSuspendedEffects.indexOfKey(type->timeLow);
7419    if (suspend) {
7420        if (index >= 0) {
7421            desc = mSuspendedEffects.valueAt(index);
7422        } else {
7423            desc = new SuspendedEffectDesc();
7424            memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7425            mSuspendedEffects.add(type->timeLow, desc);
7426            ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
7427        }
7428        if (desc->mRefCount++ == 0) {
7429            sp<EffectModule> effect = getEffectIfEnabled(type);
7430            if (effect != 0) {
7431                desc->mEffect = effect;
7432                effect->setSuspended(true);
7433                effect->setEnabled(false);
7434            }
7435        }
7436    } else {
7437        if (index < 0) {
7438            return;
7439        }
7440        desc = mSuspendedEffects.valueAt(index);
7441        if (desc->mRefCount <= 0) {
7442            ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7443            desc->mRefCount = 1;
7444        }
7445        if (--desc->mRefCount == 0) {
7446            ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7447            if (desc->mEffect != 0) {
7448                sp<EffectModule> effect = desc->mEffect.promote();
7449                if (effect != 0) {
7450                    effect->setSuspended(false);
7451                    sp<EffectHandle> handle = effect->controlHandle();
7452                    if (handle != 0) {
7453                        effect->setEnabled(handle->enabled());
7454                    }
7455                }
7456                desc->mEffect.clear();
7457            }
7458            mSuspendedEffects.removeItemsAt(index);
7459        }
7460    }
7461}
7462
7463// must be called with ThreadBase::mLock held
7464void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7465{
7466    sp<SuspendedEffectDesc> desc;
7467
7468    int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7469    if (suspend) {
7470        if (index >= 0) {
7471            desc = mSuspendedEffects.valueAt(index);
7472        } else {
7473            desc = new SuspendedEffectDesc();
7474            mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
7475            ALOGV("setEffectSuspendedAll_l() add entry for 0");
7476        }
7477        if (desc->mRefCount++ == 0) {
7478            Vector< sp<EffectModule> > effects;
7479            getSuspendEligibleEffects(effects);
7480            for (size_t i = 0; i < effects.size(); i++) {
7481                setEffectSuspended_l(&effects[i]->desc().type, true);
7482            }
7483        }
7484    } else {
7485        if (index < 0) {
7486            return;
7487        }
7488        desc = mSuspendedEffects.valueAt(index);
7489        if (desc->mRefCount <= 0) {
7490            ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7491            desc->mRefCount = 1;
7492        }
7493        if (--desc->mRefCount == 0) {
7494            Vector<const effect_uuid_t *> types;
7495            for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7496                if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7497                    continue;
7498                }
7499                types.add(&mSuspendedEffects.valueAt(i)->mType);
7500            }
7501            for (size_t i = 0; i < types.size(); i++) {
7502                setEffectSuspended_l(types[i], false);
7503            }
7504            ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7505            mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7506        }
7507    }
7508}
7509
7510
7511// The volume effect is used for automated tests only
7512#ifndef OPENSL_ES_H_
7513static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7514                                            { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7515const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7516#endif //OPENSL_ES_H_
7517
7518bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7519{
7520    // auxiliary effects and visualizer are never suspended on output mix
7521    if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7522        (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
7523         (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7524         (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
7525        return false;
7526    }
7527    return true;
7528}
7529
7530void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
7531{
7532    effects.clear();
7533    for (size_t i = 0; i < mEffects.size(); i++) {
7534        if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7535            effects.add(mEffects[i]);
7536        }
7537    }
7538}
7539
7540sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7541                                                            const effect_uuid_t *type)
7542{
7543    sp<EffectModule> effect = getEffectFromType_l(type);
7544    return effect != 0 && effect->isEnabled() ? effect : 0;
7545}
7546
7547void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7548                                                            bool enabled)
7549{
7550    int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7551    if (enabled) {
7552        if (index < 0) {
7553            // if the effect is not suspend check if all effects are suspended
7554            index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7555            if (index < 0) {
7556                return;
7557            }
7558            if (!isEffectEligibleForSuspend(effect->desc())) {
7559                return;
7560            }
7561            setEffectSuspended_l(&effect->desc().type, enabled);
7562            index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7563            if (index < 0) {
7564                ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7565                return;
7566            }
7567        }
7568        ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
7569             effect->desc().type.timeLow);
7570        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7571        // if effect is requested to suspended but was not yet enabled, supend it now.
7572        if (desc->mEffect == 0) {
7573            desc->mEffect = effect;
7574            effect->setEnabled(false);
7575            effect->setSuspended(true);
7576        }
7577    } else {
7578        if (index < 0) {
7579            return;
7580        }
7581        ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
7582             effect->desc().type.timeLow);
7583        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7584        desc->mEffect.clear();
7585        effect->setSuspended(false);
7586    }
7587}
7588
7589#undef LOG_TAG
7590#define LOG_TAG "AudioFlinger"
7591
7592// ----------------------------------------------------------------------------
7593
7594status_t AudioFlinger::onTransact(
7595        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7596{
7597    return BnAudioFlinger::onTransact(code, data, reply, flags);
7598}
7599
7600}; // namespace android
7601