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