AudioFlinger.cpp revision 1579d7948117e3e6541b0cfda02cc5234a3280ea
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) const
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) const
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) const
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) const
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        mFormat(format),
3262        mFlags(flags & ~SYSTEM_FLAGS_MASK),
3263        mSessionId(sessionId)
3264        // mChannelCount
3265        // mChannelMask
3266{
3267    ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3268
3269    // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3270   size_t size = sizeof(audio_track_cblk_t);
3271   uint8_t channelCount = popcount(channelMask);
3272   size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3273   if (sharedBuffer == 0) {
3274       size += bufferSize;
3275   }
3276
3277   if (client != NULL) {
3278        mCblkMemory = client->heap()->allocate(size);
3279        if (mCblkMemory != 0) {
3280            mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3281            if (mCblk != NULL) { // construct the shared structure in-place.
3282                new(mCblk) audio_track_cblk_t();
3283                // clear all buffers
3284                mCblk->frameCount = frameCount;
3285                mCblk->sampleRate = sampleRate;
3286                mChannelCount = channelCount;
3287                mChannelMask = channelMask;
3288                if (sharedBuffer == 0) {
3289                    mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3290                    memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3291                    // Force underrun condition to avoid false underrun callback until first data is
3292                    // written to buffer (other flags are cleared)
3293                    mCblk->flags = CBLK_UNDERRUN_ON;
3294                } else {
3295                    mBuffer = sharedBuffer->pointer();
3296                }
3297                mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3298            }
3299        } else {
3300            ALOGE("not enough memory for AudioTrack size=%u", size);
3301            client->heap()->dump("AudioTrack");
3302            return;
3303        }
3304   } else {
3305       mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3306           // construct the shared structure in-place.
3307           new(mCblk) audio_track_cblk_t();
3308           // clear all buffers
3309           mCblk->frameCount = frameCount;
3310           mCblk->sampleRate = sampleRate;
3311           mChannelCount = channelCount;
3312           mChannelMask = channelMask;
3313           mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3314           memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3315           // Force underrun condition to avoid false underrun callback until first data is
3316           // written to buffer (other flags are cleared)
3317           mCblk->flags = CBLK_UNDERRUN_ON;
3318           mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3319   }
3320}
3321
3322AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3323{
3324    if (mCblk != NULL) {
3325        mCblk->~audio_track_cblk_t();   // destroy our shared-structure.
3326        if (mClient == NULL) {
3327            delete mCblk;
3328        }
3329    }
3330    mCblkMemory.clear();            // and free the shared memory
3331    if (mClient != 0) {
3332        // Client destructor must run with AudioFlinger mutex locked
3333        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3334        // If the client's reference count drops to zero, the associated destructor
3335        // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3336        // relying on the automatic clear() at end of scope.
3337        mClient.clear();
3338    }
3339}
3340
3341void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3342{
3343    buffer->raw = NULL;
3344    mFrameCount = buffer->frameCount;
3345    step();
3346    buffer->frameCount = 0;
3347}
3348
3349bool AudioFlinger::ThreadBase::TrackBase::step() {
3350    bool result;
3351    audio_track_cblk_t* cblk = this->cblk();
3352
3353    result = cblk->stepServer(mFrameCount);
3354    if (!result) {
3355        ALOGV("stepServer failed acquiring cblk mutex");
3356        mFlags |= STEPSERVER_FAILED;
3357    }
3358    return result;
3359}
3360
3361void AudioFlinger::ThreadBase::TrackBase::reset() {
3362    audio_track_cblk_t* cblk = this->cblk();
3363
3364    cblk->user = 0;
3365    cblk->server = 0;
3366    cblk->userBase = 0;
3367    cblk->serverBase = 0;
3368    mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
3369    ALOGV("TrackBase::reset");
3370}
3371
3372sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3373{
3374    return mCblkMemory;
3375}
3376
3377int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3378    return (int)mCblk->sampleRate;
3379}
3380
3381int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
3382    return (const int)mChannelCount;
3383}
3384
3385uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3386    return mChannelMask;
3387}
3388
3389void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3390    audio_track_cblk_t* cblk = this->cblk();
3391    size_t frameSize = cblk->frameSize;
3392    int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3393    int8_t *bufferEnd = bufferStart + frames * frameSize;
3394
3395    // Check validity of returned pointer in case the track control block would have been corrupted.
3396    if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3397        ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
3398        ALOGE("TrackBase::getBuffer buffer out of range:\n    start: %p, end %p , mBuffer %p mBufferEnd %p\n    \
3399                server %d, serverBase %d, user %d, userBase %d",
3400                bufferStart, bufferEnd, mBuffer, mBufferEnd,
3401                cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
3402        return NULL;
3403    }
3404
3405    return bufferStart;
3406}
3407
3408// ----------------------------------------------------------------------------
3409
3410// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3411AudioFlinger::PlaybackThread::Track::Track(
3412            const wp<ThreadBase>& thread,
3413            const sp<Client>& client,
3414            audio_stream_type_t streamType,
3415            uint32_t sampleRate,
3416            audio_format_t format,
3417            uint32_t channelMask,
3418            int frameCount,
3419            const sp<IMemory>& sharedBuffer,
3420            int sessionId)
3421    :   TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
3422    mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3423    mAuxEffectId(0), mHasVolumeController(false)
3424{
3425    if (mCblk != NULL) {
3426        sp<ThreadBase> baseThread = thread.promote();
3427        if (baseThread != 0) {
3428            PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3429            mName = playbackThread->getTrackName_l();
3430            mMainBuffer = playbackThread->mixBuffer();
3431        }
3432        ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3433        if (mName < 0) {
3434            ALOGE("no more track names available");
3435        }
3436        mStreamType = streamType;
3437        // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3438        // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
3439        mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
3440    }
3441}
3442
3443AudioFlinger::PlaybackThread::Track::~Track()
3444{
3445    ALOGV("PlaybackThread::Track destructor");
3446    sp<ThreadBase> thread = mThread.promote();
3447    if (thread != 0) {
3448        Mutex::Autolock _l(thread->mLock);
3449        mState = TERMINATED;
3450    }
3451}
3452
3453void AudioFlinger::PlaybackThread::Track::destroy()
3454{
3455    // NOTE: destroyTrack_l() can remove a strong reference to this Track
3456    // by removing it from mTracks vector, so there is a risk that this Tracks's
3457    // desctructor is called. As the destructor needs to lock mLock,
3458    // we must acquire a strong reference on this Track before locking mLock
3459    // here so that the destructor is called only when exiting this function.
3460    // On the other hand, as long as Track::destroy() is only called by
3461    // TrackHandle destructor, the TrackHandle still holds a strong ref on
3462    // this Track with its member mTrack.
3463    sp<Track> keep(this);
3464    { // scope for mLock
3465        sp<ThreadBase> thread = mThread.promote();
3466        if (thread != 0) {
3467            if (!isOutputTrack()) {
3468                if (mState == ACTIVE || mState == RESUMING) {
3469                    AudioSystem::stopOutput(thread->id(),
3470                                            (audio_stream_type_t)mStreamType,
3471                                            mSessionId);
3472
3473                    // to track the speaker usage
3474                    addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
3475                }
3476                AudioSystem::releaseOutput(thread->id());
3477            }
3478            Mutex::Autolock _l(thread->mLock);
3479            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3480            playbackThread->destroyTrack_l(this);
3481        }
3482    }
3483}
3484
3485void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3486{
3487    uint32_t vlr = mCblk->getVolumeLR();
3488    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",
3489            mName - AudioMixer::TRACK0,
3490            (mClient == 0) ? getpid() : mClient->pid(),
3491            mStreamType,
3492            mFormat,
3493            mChannelMask,
3494            mSessionId,
3495            mFrameCount,
3496            mState,
3497            mMute,
3498            mFillingUpStatus,
3499            mCblk->sampleRate,
3500            vlr & 0xFFFF,
3501            vlr >> 16,
3502            mCblk->server,
3503            mCblk->user,
3504            (int)mMainBuffer,
3505            (int)mAuxBuffer);
3506}
3507
3508status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3509{
3510     audio_track_cblk_t* cblk = this->cblk();
3511     uint32_t framesReady;
3512     uint32_t framesReq = buffer->frameCount;
3513
3514     // Check if last stepServer failed, try to step now
3515     if (mFlags & TrackBase::STEPSERVER_FAILED) {
3516         if (!step())  goto getNextBuffer_exit;
3517         ALOGV("stepServer recovered");
3518         mFlags &= ~TrackBase::STEPSERVER_FAILED;
3519     }
3520
3521     framesReady = cblk->framesReady();
3522
3523     if (CC_LIKELY(framesReady)) {
3524        uint32_t s = cblk->server;
3525        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3526
3527        bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3528        if (framesReq > framesReady) {
3529            framesReq = framesReady;
3530        }
3531        if (s + framesReq > bufferEnd) {
3532            framesReq = bufferEnd - s;
3533        }
3534
3535         buffer->raw = getBuffer(s, framesReq);
3536         if (buffer->raw == NULL) goto getNextBuffer_exit;
3537
3538         buffer->frameCount = framesReq;
3539        return NO_ERROR;
3540     }
3541
3542getNextBuffer_exit:
3543     buffer->raw = NULL;
3544     buffer->frameCount = 0;
3545     ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3546     return NOT_ENOUGH_DATA;
3547}
3548
3549bool AudioFlinger::PlaybackThread::Track::isReady() const {
3550    if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
3551
3552    if (mCblk->framesReady() >= mCblk->frameCount ||
3553            (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3554        mFillingUpStatus = FS_FILLED;
3555        android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3556        return true;
3557    }
3558    return false;
3559}
3560
3561status_t AudioFlinger::PlaybackThread::Track::start()
3562{
3563    status_t status = NO_ERROR;
3564    ALOGV("start(%d), calling thread %d session %d",
3565            mName, IPCThreadState::self()->getCallingPid(), mSessionId);
3566    sp<ThreadBase> thread = mThread.promote();
3567    if (thread != 0) {
3568        Mutex::Autolock _l(thread->mLock);
3569        track_state state = mState;
3570        // here the track could be either new, or restarted
3571        // in both cases "unstop" the track
3572        if (mState == PAUSED) {
3573            mState = TrackBase::RESUMING;
3574            ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3575        } else {
3576            mState = TrackBase::ACTIVE;
3577            ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
3578        }
3579
3580        if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3581            thread->mLock.unlock();
3582            status = AudioSystem::startOutput(thread->id(),
3583                                              (audio_stream_type_t)mStreamType,
3584                                              mSessionId);
3585            thread->mLock.lock();
3586
3587            // to track the speaker usage
3588            if (status == NO_ERROR) {
3589                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3590            }
3591        }
3592        if (status == NO_ERROR) {
3593            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3594            playbackThread->addTrack_l(this);
3595        } else {
3596            mState = state;
3597        }
3598    } else {
3599        status = BAD_VALUE;
3600    }
3601    return status;
3602}
3603
3604void AudioFlinger::PlaybackThread::Track::stop()
3605{
3606    ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3607    sp<ThreadBase> thread = mThread.promote();
3608    if (thread != 0) {
3609        Mutex::Autolock _l(thread->mLock);
3610        track_state state = mState;
3611        if (mState > STOPPED) {
3612            mState = STOPPED;
3613            // If the track is not active (PAUSED and buffers full), flush buffers
3614            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3615            if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3616                reset();
3617            }
3618            ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3619        }
3620        if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3621            thread->mLock.unlock();
3622            AudioSystem::stopOutput(thread->id(),
3623                                    (audio_stream_type_t)mStreamType,
3624                                    mSessionId);
3625            thread->mLock.lock();
3626
3627            // to track the speaker usage
3628            addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
3629        }
3630    }
3631}
3632
3633void AudioFlinger::PlaybackThread::Track::pause()
3634{
3635    ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3636    sp<ThreadBase> thread = mThread.promote();
3637    if (thread != 0) {
3638        Mutex::Autolock _l(thread->mLock);
3639        if (mState == ACTIVE || mState == RESUMING) {
3640            mState = PAUSING;
3641            ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3642            if (!isOutputTrack()) {
3643                thread->mLock.unlock();
3644                AudioSystem::stopOutput(thread->id(),
3645                                        (audio_stream_type_t)mStreamType,
3646                                        mSessionId);
3647                thread->mLock.lock();
3648
3649                // to track the speaker usage
3650                addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
3651            }
3652        }
3653    }
3654}
3655
3656void AudioFlinger::PlaybackThread::Track::flush()
3657{
3658    ALOGV("flush(%d)", mName);
3659    sp<ThreadBase> thread = mThread.promote();
3660    if (thread != 0) {
3661        Mutex::Autolock _l(thread->mLock);
3662        if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3663            return;
3664        }
3665        // No point remaining in PAUSED state after a flush => go to
3666        // STOPPED state
3667        mState = STOPPED;
3668
3669        // do not reset the track if it is still in the process of being stopped or paused.
3670        // this will be done by prepareTracks_l() when the track is stopped.
3671        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3672        if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3673            reset();
3674        }
3675    }
3676}
3677
3678void AudioFlinger::PlaybackThread::Track::reset()
3679{
3680    // Do not reset twice to avoid discarding data written just after a flush and before
3681    // the audioflinger thread detects the track is stopped.
3682    if (!mResetDone) {
3683        TrackBase::reset();
3684        // Force underrun condition to avoid false underrun callback until first data is
3685        // written to buffer
3686        android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3687        android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
3688        mFillingUpStatus = FS_FILLING;
3689        mResetDone = true;
3690    }
3691}
3692
3693void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3694{
3695    mMute = muted;
3696}
3697
3698status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3699{
3700    status_t status = DEAD_OBJECT;
3701    sp<ThreadBase> thread = mThread.promote();
3702    if (thread != 0) {
3703       PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3704       status = playbackThread->attachAuxEffect(this, EffectId);
3705    }
3706    return status;
3707}
3708
3709void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3710{
3711    mAuxEffectId = EffectId;
3712    mAuxBuffer = buffer;
3713}
3714
3715// ----------------------------------------------------------------------------
3716
3717// RecordTrack constructor must be called with AudioFlinger::mLock held
3718AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3719            const wp<ThreadBase>& thread,
3720            const sp<Client>& client,
3721            uint32_t sampleRate,
3722            audio_format_t format,
3723            uint32_t channelMask,
3724            int frameCount,
3725            uint32_t flags,
3726            int sessionId)
3727    :   TrackBase(thread, client, sampleRate, format,
3728                  channelMask, frameCount, flags, 0, sessionId),
3729        mOverflow(false)
3730{
3731    if (mCblk != NULL) {
3732       ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
3733       if (format == AUDIO_FORMAT_PCM_16_BIT) {
3734           mCblk->frameSize = mChannelCount * sizeof(int16_t);
3735       } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
3736           mCblk->frameSize = mChannelCount * sizeof(int8_t);
3737       } else {
3738           mCblk->frameSize = sizeof(int8_t);
3739       }
3740    }
3741}
3742
3743AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3744{
3745    sp<ThreadBase> thread = mThread.promote();
3746    if (thread != 0) {
3747        AudioSystem::releaseInput(thread->id());
3748    }
3749}
3750
3751status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3752{
3753    audio_track_cblk_t* cblk = this->cblk();
3754    uint32_t framesAvail;
3755    uint32_t framesReq = buffer->frameCount;
3756
3757     // Check if last stepServer failed, try to step now
3758    if (mFlags & TrackBase::STEPSERVER_FAILED) {
3759        if (!step()) goto getNextBuffer_exit;
3760        ALOGV("stepServer recovered");
3761        mFlags &= ~TrackBase::STEPSERVER_FAILED;
3762    }
3763
3764    framesAvail = cblk->framesAvailable_l();
3765
3766    if (CC_LIKELY(framesAvail)) {
3767        uint32_t s = cblk->server;
3768        uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3769
3770        if (framesReq > framesAvail) {
3771            framesReq = framesAvail;
3772        }
3773        if (s + framesReq > bufferEnd) {
3774            framesReq = bufferEnd - s;
3775        }
3776
3777        buffer->raw = getBuffer(s, framesReq);
3778        if (buffer->raw == NULL) goto getNextBuffer_exit;
3779
3780        buffer->frameCount = framesReq;
3781        return NO_ERROR;
3782    }
3783
3784getNextBuffer_exit:
3785    buffer->raw = NULL;
3786    buffer->frameCount = 0;
3787    return NOT_ENOUGH_DATA;
3788}
3789
3790status_t AudioFlinger::RecordThread::RecordTrack::start()
3791{
3792    sp<ThreadBase> thread = mThread.promote();
3793    if (thread != 0) {
3794        RecordThread *recordThread = (RecordThread *)thread.get();
3795        return recordThread->start(this);
3796    } else {
3797        return BAD_VALUE;
3798    }
3799}
3800
3801void AudioFlinger::RecordThread::RecordTrack::stop()
3802{
3803    sp<ThreadBase> thread = mThread.promote();
3804    if (thread != 0) {
3805        RecordThread *recordThread = (RecordThread *)thread.get();
3806        recordThread->stop(this);
3807        TrackBase::reset();
3808        // Force overerrun condition to avoid false overrun callback until first data is
3809        // read from buffer
3810        android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
3811    }
3812}
3813
3814void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3815{
3816    snprintf(buffer, size, "   %05d %03u 0x%08x %05d   %04u %01d %05u  %08x %08x\n",
3817            (mClient == 0) ? getpid() : mClient->pid(),
3818            mFormat,
3819            mChannelMask,
3820            mSessionId,
3821            mFrameCount,
3822            mState,
3823            mCblk->sampleRate,
3824            mCblk->server,
3825            mCblk->user);
3826}
3827
3828
3829// ----------------------------------------------------------------------------
3830
3831AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3832            const wp<ThreadBase>& thread,
3833            DuplicatingThread *sourceThread,
3834            uint32_t sampleRate,
3835            audio_format_t format,
3836            uint32_t channelMask,
3837            int frameCount)
3838    :   Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
3839    mActive(false), mSourceThread(sourceThread)
3840{
3841
3842    PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3843    if (mCblk != NULL) {
3844        mCblk->flags |= CBLK_DIRECTION_OUT;
3845        mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3846        mOutBuffer.frameCount = 0;
3847        playbackThread->mTracks.add(this);
3848        ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3849                "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3850                mCblk, mBuffer, mCblk->buffers,
3851                mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
3852    } else {
3853        ALOGW("Error creating output track on thread %p", playbackThread);
3854    }
3855}
3856
3857AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3858{
3859    clearBufferQueue();
3860}
3861
3862status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3863{
3864    status_t status = Track::start();
3865    if (status != NO_ERROR) {
3866        return status;
3867    }
3868
3869    mActive = true;
3870    mRetryCount = 127;
3871    return status;
3872}
3873
3874void AudioFlinger::PlaybackThread::OutputTrack::stop()
3875{
3876    Track::stop();
3877    clearBufferQueue();
3878    mOutBuffer.frameCount = 0;
3879    mActive = false;
3880}
3881
3882bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3883{
3884    Buffer *pInBuffer;
3885    Buffer inBuffer;
3886    uint32_t channelCount = mChannelCount;
3887    bool outputBufferFull = false;
3888    inBuffer.frameCount = frames;
3889    inBuffer.i16 = data;
3890
3891    uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3892
3893    if (!mActive && frames != 0) {
3894        start();
3895        sp<ThreadBase> thread = mThread.promote();
3896        if (thread != 0) {
3897            MixerThread *mixerThread = (MixerThread *)thread.get();
3898            if (mCblk->frameCount > frames){
3899                if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3900                    uint32_t startFrames = (mCblk->frameCount - frames);
3901                    pInBuffer = new Buffer;
3902                    pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3903                    pInBuffer->frameCount = startFrames;
3904                    pInBuffer->i16 = pInBuffer->mBuffer;
3905                    memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3906                    mBufferQueue.add(pInBuffer);
3907                } else {
3908                    ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
3909                }
3910            }
3911        }
3912    }
3913
3914    while (waitTimeLeftMs) {
3915        // First write pending buffers, then new data
3916        if (mBufferQueue.size()) {
3917            pInBuffer = mBufferQueue.itemAt(0);
3918        } else {
3919            pInBuffer = &inBuffer;
3920        }
3921
3922        if (pInBuffer->frameCount == 0) {
3923            break;
3924        }
3925
3926        if (mOutBuffer.frameCount == 0) {
3927            mOutBuffer.frameCount = pInBuffer->frameCount;
3928            nsecs_t startTime = systemTime();
3929            if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
3930                ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
3931                outputBufferFull = true;
3932                break;
3933            }
3934            uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3935            if (waitTimeLeftMs >= waitTimeMs) {
3936                waitTimeLeftMs -= waitTimeMs;
3937            } else {
3938                waitTimeLeftMs = 0;
3939            }
3940        }
3941
3942        uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3943        memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3944        mCblk->stepUser(outFrames);
3945        pInBuffer->frameCount -= outFrames;
3946        pInBuffer->i16 += outFrames * channelCount;
3947        mOutBuffer.frameCount -= outFrames;
3948        mOutBuffer.i16 += outFrames * channelCount;
3949
3950        if (pInBuffer->frameCount == 0) {
3951            if (mBufferQueue.size()) {
3952                mBufferQueue.removeAt(0);
3953                delete [] pInBuffer->mBuffer;
3954                delete pInBuffer;
3955                ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3956            } else {
3957                break;
3958            }
3959        }
3960    }
3961
3962    // If we could not write all frames, allocate a buffer and queue it for next time.
3963    if (inBuffer.frameCount) {
3964        sp<ThreadBase> thread = mThread.promote();
3965        if (thread != 0 && !thread->standby()) {
3966            if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3967                pInBuffer = new Buffer;
3968                pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3969                pInBuffer->frameCount = inBuffer.frameCount;
3970                pInBuffer->i16 = pInBuffer->mBuffer;
3971                memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3972                mBufferQueue.add(pInBuffer);
3973                ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3974            } else {
3975                ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3976            }
3977        }
3978    }
3979
3980    // Calling write() with a 0 length buffer, means that no more data will be written:
3981    // If no more buffers are pending, fill output track buffer to make sure it is started
3982    // by output mixer.
3983    if (frames == 0 && mBufferQueue.size() == 0) {
3984        if (mCblk->user < mCblk->frameCount) {
3985            frames = mCblk->frameCount - mCblk->user;
3986            pInBuffer = new Buffer;
3987            pInBuffer->mBuffer = new int16_t[frames * channelCount];
3988            pInBuffer->frameCount = frames;
3989            pInBuffer->i16 = pInBuffer->mBuffer;
3990            memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3991            mBufferQueue.add(pInBuffer);
3992        } else if (mActive) {
3993            stop();
3994        }
3995    }
3996
3997    return outputBufferFull;
3998}
3999
4000status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4001{
4002    int active;
4003    status_t result;
4004    audio_track_cblk_t* cblk = mCblk;
4005    uint32_t framesReq = buffer->frameCount;
4006
4007//    ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
4008    buffer->frameCount  = 0;
4009
4010    uint32_t framesAvail = cblk->framesAvailable();
4011
4012
4013    if (framesAvail == 0) {
4014        Mutex::Autolock _l(cblk->lock);
4015        goto start_loop_here;
4016        while (framesAvail == 0) {
4017            active = mActive;
4018            if (CC_UNLIKELY(!active)) {
4019                ALOGV("Not active and NO_MORE_BUFFERS");
4020                return NO_MORE_BUFFERS;
4021            }
4022            result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4023            if (result != NO_ERROR) {
4024                return NO_MORE_BUFFERS;
4025            }
4026            // read the server count again
4027        start_loop_here:
4028            framesAvail = cblk->framesAvailable_l();
4029        }
4030    }
4031
4032//    if (framesAvail < framesReq) {
4033//        return NO_MORE_BUFFERS;
4034//    }
4035
4036    if (framesReq > framesAvail) {
4037        framesReq = framesAvail;
4038    }
4039
4040    uint32_t u = cblk->user;
4041    uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4042
4043    if (u + framesReq > bufferEnd) {
4044        framesReq = bufferEnd - u;
4045    }
4046
4047    buffer->frameCount  = framesReq;
4048    buffer->raw         = (void *)cblk->buffer(u);
4049    return NO_ERROR;
4050}
4051
4052
4053void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4054{
4055    size_t size = mBufferQueue.size();
4056    Buffer *pBuffer;
4057
4058    for (size_t i = 0; i < size; i++) {
4059        pBuffer = mBufferQueue.itemAt(i);
4060        delete [] pBuffer->mBuffer;
4061        delete pBuffer;
4062    }
4063    mBufferQueue.clear();
4064}
4065
4066// ----------------------------------------------------------------------------
4067
4068AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4069    :   RefBase(),
4070        mAudioFlinger(audioFlinger),
4071        mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4072        mPid(pid)
4073{
4074    // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4075}
4076
4077// Client destructor must be called with AudioFlinger::mLock held
4078AudioFlinger::Client::~Client()
4079{
4080    mAudioFlinger->removeClient_l(mPid);
4081}
4082
4083sp<MemoryDealer> AudioFlinger::Client::heap() const
4084{
4085    return mMemoryDealer;
4086}
4087
4088// ----------------------------------------------------------------------------
4089
4090AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4091                                                     const sp<IAudioFlingerClient>& client,
4092                                                     pid_t pid)
4093    : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
4094{
4095}
4096
4097AudioFlinger::NotificationClient::~NotificationClient()
4098{
4099}
4100
4101void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4102{
4103    sp<NotificationClient> keep(this);
4104    {
4105        mAudioFlinger->removeNotificationClient(mPid);
4106    }
4107}
4108
4109// ----------------------------------------------------------------------------
4110
4111AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4112    : BnAudioTrack(),
4113      mTrack(track)
4114{
4115}
4116
4117AudioFlinger::TrackHandle::~TrackHandle() {
4118    // just stop the track on deletion, associated resources
4119    // will be freed from the main thread once all pending buffers have
4120    // been played. Unless it's not in the active track list, in which
4121    // case we free everything now...
4122    mTrack->destroy();
4123}
4124
4125sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4126    return mTrack->getCblk();
4127}
4128
4129status_t AudioFlinger::TrackHandle::start() {
4130    return mTrack->start();
4131}
4132
4133void AudioFlinger::TrackHandle::stop() {
4134    mTrack->stop();
4135}
4136
4137void AudioFlinger::TrackHandle::flush() {
4138    mTrack->flush();
4139}
4140
4141void AudioFlinger::TrackHandle::mute(bool e) {
4142    mTrack->mute(e);
4143}
4144
4145void AudioFlinger::TrackHandle::pause() {
4146    mTrack->pause();
4147}
4148
4149status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4150{
4151    return mTrack->attachAuxEffect(EffectId);
4152}
4153
4154status_t AudioFlinger::TrackHandle::onTransact(
4155    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4156{
4157    return BnAudioTrack::onTransact(code, data, reply, flags);
4158}
4159
4160// ----------------------------------------------------------------------------
4161
4162sp<IAudioRecord> AudioFlinger::openRecord(
4163        pid_t pid,
4164        int input,
4165        uint32_t sampleRate,
4166        audio_format_t format,
4167        uint32_t channelMask,
4168        int frameCount,
4169        uint32_t flags,
4170        int *sessionId,
4171        status_t *status)
4172{
4173    sp<RecordThread::RecordTrack> recordTrack;
4174    sp<RecordHandle> recordHandle;
4175    sp<Client> client;
4176    wp<Client> wclient;
4177    status_t lStatus;
4178    RecordThread *thread;
4179    size_t inFrameCount;
4180    int lSessionId;
4181
4182    // check calling permissions
4183    if (!recordingAllowed()) {
4184        lStatus = PERMISSION_DENIED;
4185        goto Exit;
4186    }
4187
4188    // add client to list
4189    { // scope for mLock
4190        Mutex::Autolock _l(mLock);
4191        thread = checkRecordThread_l(input);
4192        if (thread == NULL) {
4193            lStatus = BAD_VALUE;
4194            goto Exit;
4195        }
4196
4197        wclient = mClients.valueFor(pid);
4198        if (wclient != NULL) {
4199            client = wclient.promote();
4200        } else {
4201            client = new Client(this, pid);
4202            mClients.add(pid, client);
4203        }
4204
4205        // If no audio session id is provided, create one here
4206        if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
4207            lSessionId = *sessionId;
4208        } else {
4209            lSessionId = nextUniqueId();
4210            if (sessionId != NULL) {
4211                *sessionId = lSessionId;
4212            }
4213        }
4214        // create new record track. The record track uses one track in mHardwareMixerThread by convention.
4215        recordTrack = thread->createRecordTrack_l(client,
4216                                                sampleRate,
4217                                                format,
4218                                                channelMask,
4219                                                frameCount,
4220                                                flags,
4221                                                lSessionId,
4222                                                &lStatus);
4223    }
4224    if (lStatus != NO_ERROR) {
4225        // remove local strong reference to Client before deleting the RecordTrack so that the Client
4226        // destructor is called by the TrackBase destructor with mLock held
4227        client.clear();
4228        recordTrack.clear();
4229        goto Exit;
4230    }
4231
4232    // return to handle to client
4233    recordHandle = new RecordHandle(recordTrack);
4234    lStatus = NO_ERROR;
4235
4236Exit:
4237    if (status) {
4238        *status = lStatus;
4239    }
4240    return recordHandle;
4241}
4242
4243// ----------------------------------------------------------------------------
4244
4245AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4246    : BnAudioRecord(),
4247    mRecordTrack(recordTrack)
4248{
4249}
4250
4251AudioFlinger::RecordHandle::~RecordHandle() {
4252    stop();
4253}
4254
4255sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4256    return mRecordTrack->getCblk();
4257}
4258
4259status_t AudioFlinger::RecordHandle::start() {
4260    ALOGV("RecordHandle::start()");
4261    return mRecordTrack->start();
4262}
4263
4264void AudioFlinger::RecordHandle::stop() {
4265    ALOGV("RecordHandle::stop()");
4266    mRecordTrack->stop();
4267}
4268
4269status_t AudioFlinger::RecordHandle::onTransact(
4270    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4271{
4272    return BnAudioRecord::onTransact(code, data, reply, flags);
4273}
4274
4275// ----------------------------------------------------------------------------
4276
4277AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4278                                         AudioStreamIn *input,
4279                                         uint32_t sampleRate,
4280                                         uint32_t channels,
4281                                         int id,
4282                                         uint32_t device) :
4283    ThreadBase(audioFlinger, id, device, RECORD),
4284    mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4285    // mRsmpInIndex and mInputBytes set by readInputParameters()
4286    mReqChannelCount(popcount(channels)),
4287    mReqSampleRate(sampleRate)
4288    // mBytesRead is only meaningful while active, and so is cleared in start()
4289    // (but might be better to also clear here for dump?)
4290{
4291    snprintf(mName, kNameLength, "AudioIn_%d", id);
4292
4293    readInputParameters();
4294}
4295
4296
4297AudioFlinger::RecordThread::~RecordThread()
4298{
4299    delete[] mRsmpInBuffer;
4300    delete mResampler;
4301    delete[] mRsmpOutBuffer;
4302}
4303
4304void AudioFlinger::RecordThread::onFirstRef()
4305{
4306    run(mName, PRIORITY_URGENT_AUDIO);
4307}
4308
4309status_t AudioFlinger::RecordThread::readyToRun()
4310{
4311    status_t status = initCheck();
4312    ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4313    return status;
4314}
4315
4316bool AudioFlinger::RecordThread::threadLoop()
4317{
4318    AudioBufferProvider::Buffer buffer;
4319    sp<RecordTrack> activeTrack;
4320    Vector< sp<EffectChain> > effectChains;
4321
4322    nsecs_t lastWarning = 0;
4323
4324    acquireWakeLock();
4325
4326    // start recording
4327    while (!exitPending()) {
4328
4329        processConfigEvents();
4330
4331        { // scope for mLock
4332            Mutex::Autolock _l(mLock);
4333            checkForNewParameters_l();
4334            if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4335                if (!mStandby) {
4336                    mInput->stream->common.standby(&mInput->stream->common);
4337                    mStandby = true;
4338                }
4339
4340                if (exitPending()) break;
4341
4342                releaseWakeLock_l();
4343                ALOGV("RecordThread: loop stopping");
4344                // go to sleep
4345                mWaitWorkCV.wait(mLock);
4346                ALOGV("RecordThread: loop starting");
4347                acquireWakeLock_l();
4348                continue;
4349            }
4350            if (mActiveTrack != 0) {
4351                if (mActiveTrack->mState == TrackBase::PAUSING) {
4352                    if (!mStandby) {
4353                        mInput->stream->common.standby(&mInput->stream->common);
4354                        mStandby = true;
4355                    }
4356                    mActiveTrack.clear();
4357                    mStartStopCond.broadcast();
4358                } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4359                    if (mReqChannelCount != mActiveTrack->channelCount()) {
4360                        mActiveTrack.clear();
4361                        mStartStopCond.broadcast();
4362                    } else if (mBytesRead != 0) {
4363                        // record start succeeds only if first read from audio input
4364                        // succeeds
4365                        if (mBytesRead > 0) {
4366                            mActiveTrack->mState = TrackBase::ACTIVE;
4367                        } else {
4368                            mActiveTrack.clear();
4369                        }
4370                        mStartStopCond.broadcast();
4371                    }
4372                    mStandby = false;
4373                }
4374            }
4375            lockEffectChains_l(effectChains);
4376        }
4377
4378        if (mActiveTrack != 0) {
4379            if (mActiveTrack->mState != TrackBase::ACTIVE &&
4380                mActiveTrack->mState != TrackBase::RESUMING) {
4381                unlockEffectChains(effectChains);
4382                usleep(kRecordThreadSleepUs);
4383                continue;
4384            }
4385            for (size_t i = 0; i < effectChains.size(); i ++) {
4386                effectChains[i]->process_l();
4387            }
4388
4389            buffer.frameCount = mFrameCount;
4390            if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4391                size_t framesOut = buffer.frameCount;
4392                if (mResampler == NULL) {
4393                    // no resampling
4394                    while (framesOut) {
4395                        size_t framesIn = mFrameCount - mRsmpInIndex;
4396                        if (framesIn) {
4397                            int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4398                            int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4399                            if (framesIn > framesOut)
4400                                framesIn = framesOut;
4401                            mRsmpInIndex += framesIn;
4402                            framesOut -= framesIn;
4403                            if ((int)mChannelCount == mReqChannelCount ||
4404                                mFormat != AUDIO_FORMAT_PCM_16_BIT) {
4405                                memcpy(dst, src, framesIn * mFrameSize);
4406                            } else {
4407                                int16_t *src16 = (int16_t *)src;
4408                                int16_t *dst16 = (int16_t *)dst;
4409                                if (mChannelCount == 1) {
4410                                    while (framesIn--) {
4411                                        *dst16++ = *src16;
4412                                        *dst16++ = *src16++;
4413                                    }
4414                                } else {
4415                                    while (framesIn--) {
4416                                        *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4417                                        src16 += 2;
4418                                    }
4419                                }
4420                            }
4421                        }
4422                        if (framesOut && mFrameCount == mRsmpInIndex) {
4423                            if (framesOut == mFrameCount &&
4424                                ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
4425                                mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
4426                                framesOut = 0;
4427                            } else {
4428                                mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
4429                                mRsmpInIndex = 0;
4430                            }
4431                            if (mBytesRead < 0) {
4432                                ALOGE("Error reading audio input");
4433                                if (mActiveTrack->mState == TrackBase::ACTIVE) {
4434                                    // Force input into standby so that it tries to
4435                                    // recover at next read attempt
4436                                    mInput->stream->common.standby(&mInput->stream->common);
4437                                    usleep(kRecordThreadSleepUs);
4438                                }
4439                                mRsmpInIndex = mFrameCount;
4440                                framesOut = 0;
4441                                buffer.frameCount = 0;
4442                            }
4443                        }
4444                    }
4445                } else {
4446                    // resampling
4447
4448                    memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4449                    // alter output frame count as if we were expecting stereo samples
4450                    if (mChannelCount == 1 && mReqChannelCount == 1) {
4451                        framesOut >>= 1;
4452                    }
4453                    mResampler->resample(mRsmpOutBuffer, framesOut, this);
4454                    // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4455                    // are 32 bit aligned which should be always true.
4456                    if (mChannelCount == 2 && mReqChannelCount == 1) {
4457                        ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4458                        // the resampler always outputs stereo samples: do post stereo to mono conversion
4459                        int16_t *src = (int16_t *)mRsmpOutBuffer;
4460                        int16_t *dst = buffer.i16;
4461                        while (framesOut--) {
4462                            *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4463                            src += 2;
4464                        }
4465                    } else {
4466                        ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4467                    }
4468
4469                }
4470                mActiveTrack->releaseBuffer(&buffer);
4471                mActiveTrack->overflow();
4472            }
4473            // client isn't retrieving buffers fast enough
4474            else {
4475                if (!mActiveTrack->setOverflow()) {
4476                    nsecs_t now = systemTime();
4477                    if ((now - lastWarning) > kWarningThrottleNs) {
4478                        ALOGW("RecordThread: buffer overflow");
4479                        lastWarning = now;
4480                    }
4481                }
4482                // Release the processor for a while before asking for a new buffer.
4483                // This will give the application more chance to read from the buffer and
4484                // clear the overflow.
4485                usleep(kRecordThreadSleepUs);
4486            }
4487        }
4488        // enable changes in effect chain
4489        unlockEffectChains(effectChains);
4490        effectChains.clear();
4491    }
4492
4493    if (!mStandby) {
4494        mInput->stream->common.standby(&mInput->stream->common);
4495    }
4496    mActiveTrack.clear();
4497
4498    mStartStopCond.broadcast();
4499
4500    releaseWakeLock();
4501
4502    ALOGV("RecordThread %p exiting", this);
4503    return false;
4504}
4505
4506
4507sp<AudioFlinger::RecordThread::RecordTrack>  AudioFlinger::RecordThread::createRecordTrack_l(
4508        const sp<AudioFlinger::Client>& client,
4509        uint32_t sampleRate,
4510        audio_format_t format,
4511        int channelMask,
4512        int frameCount,
4513        uint32_t flags,
4514        int sessionId,
4515        status_t *status)
4516{
4517    sp<RecordTrack> track;
4518    status_t lStatus;
4519
4520    lStatus = initCheck();
4521    if (lStatus != NO_ERROR) {
4522        ALOGE("Audio driver not initialized.");
4523        goto Exit;
4524    }
4525
4526    { // scope for mLock
4527        Mutex::Autolock _l(mLock);
4528
4529        track = new RecordTrack(this, client, sampleRate,
4530                      format, channelMask, frameCount, flags, sessionId);
4531
4532        if (track->getCblk() == 0) {
4533            lStatus = NO_MEMORY;
4534            goto Exit;
4535        }
4536
4537        mTrack = track.get();
4538        // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4539        bool suspend = audio_is_bluetooth_sco_device(
4540                (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
4541        setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4542        setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
4543    }
4544    lStatus = NO_ERROR;
4545
4546Exit:
4547    if (status) {
4548        *status = lStatus;
4549    }
4550    return track;
4551}
4552
4553status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4554{
4555    ALOGV("RecordThread::start");
4556    sp <ThreadBase> strongMe = this;
4557    status_t status = NO_ERROR;
4558    {
4559        AutoMutex lock(mLock);
4560        if (mActiveTrack != 0) {
4561            if (recordTrack != mActiveTrack.get()) {
4562                status = -EBUSY;
4563            } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4564                mActiveTrack->mState = TrackBase::ACTIVE;
4565            }
4566            return status;
4567        }
4568
4569        recordTrack->mState = TrackBase::IDLE;
4570        mActiveTrack = recordTrack;
4571        mLock.unlock();
4572        status_t status = AudioSystem::startInput(mId);
4573        mLock.lock();
4574        if (status != NO_ERROR) {
4575            mActiveTrack.clear();
4576            return status;
4577        }
4578        mRsmpInIndex = mFrameCount;
4579        mBytesRead = 0;
4580        if (mResampler != NULL) {
4581            mResampler->reset();
4582        }
4583        mActiveTrack->mState = TrackBase::RESUMING;
4584        // signal thread to start
4585        ALOGV("Signal record thread");
4586        mWaitWorkCV.signal();
4587        // do not wait for mStartStopCond if exiting
4588        if (mExiting) {
4589            mActiveTrack.clear();
4590            status = INVALID_OPERATION;
4591            goto startError;
4592        }
4593        mStartStopCond.wait(mLock);
4594        if (mActiveTrack == 0) {
4595            ALOGV("Record failed to start");
4596            status = BAD_VALUE;
4597            goto startError;
4598        }
4599        ALOGV("Record started OK");
4600        return status;
4601    }
4602startError:
4603    AudioSystem::stopInput(mId);
4604    return status;
4605}
4606
4607void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4608    ALOGV("RecordThread::stop");
4609    sp <ThreadBase> strongMe = this;
4610    {
4611        AutoMutex lock(mLock);
4612        if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4613            mActiveTrack->mState = TrackBase::PAUSING;
4614            // do not wait for mStartStopCond if exiting
4615            if (mExiting) {
4616                return;
4617            }
4618            mStartStopCond.wait(mLock);
4619            // if we have been restarted, recordTrack == mActiveTrack.get() here
4620            if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4621                mLock.unlock();
4622                AudioSystem::stopInput(mId);
4623                mLock.lock();
4624                ALOGV("Record stopped OK");
4625            }
4626        }
4627    }
4628}
4629
4630status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4631{
4632    const size_t SIZE = 256;
4633    char buffer[SIZE];
4634    String8 result;
4635
4636    snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4637    result.append(buffer);
4638
4639    if (mActiveTrack != 0) {
4640        result.append("Active Track:\n");
4641        result.append("   Clien Fmt Chn mask   Session Buf  S SRate  Serv     User\n");
4642        mActiveTrack->dump(buffer, SIZE);
4643        result.append(buffer);
4644
4645        snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4646        result.append(buffer);
4647        snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4648        result.append(buffer);
4649        snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
4650        result.append(buffer);
4651        snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4652        result.append(buffer);
4653        snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4654        result.append(buffer);
4655
4656
4657    } else {
4658        result.append("No record client\n");
4659    }
4660    write(fd, result.string(), result.size());
4661
4662    dumpBase(fd, args);
4663    dumpEffectChains(fd, args);
4664
4665    return NO_ERROR;
4666}
4667
4668status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4669{
4670    size_t framesReq = buffer->frameCount;
4671    size_t framesReady = mFrameCount - mRsmpInIndex;
4672    int channelCount;
4673
4674    if (framesReady == 0) {
4675        mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
4676        if (mBytesRead < 0) {
4677            ALOGE("RecordThread::getNextBuffer() Error reading audio input");
4678            if (mActiveTrack->mState == TrackBase::ACTIVE) {
4679                // Force input into standby so that it tries to
4680                // recover at next read attempt
4681                mInput->stream->common.standby(&mInput->stream->common);
4682                usleep(kRecordThreadSleepUs);
4683            }
4684            buffer->raw = NULL;
4685            buffer->frameCount = 0;
4686            return NOT_ENOUGH_DATA;
4687        }
4688        mRsmpInIndex = 0;
4689        framesReady = mFrameCount;
4690    }
4691
4692    if (framesReq > framesReady) {
4693        framesReq = framesReady;
4694    }
4695
4696    if (mChannelCount == 1 && mReqChannelCount == 2) {
4697        channelCount = 1;
4698    } else {
4699        channelCount = 2;
4700    }
4701    buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4702    buffer->frameCount = framesReq;
4703    return NO_ERROR;
4704}
4705
4706void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4707{
4708    mRsmpInIndex += buffer->frameCount;
4709    buffer->frameCount = 0;
4710}
4711
4712bool AudioFlinger::RecordThread::checkForNewParameters_l()
4713{
4714    bool reconfig = false;
4715
4716    while (!mNewParameters.isEmpty()) {
4717        status_t status = NO_ERROR;
4718        String8 keyValuePair = mNewParameters[0];
4719        AudioParameter param = AudioParameter(keyValuePair);
4720        int value;
4721        audio_format_t reqFormat = mFormat;
4722        int reqSamplingRate = mReqSampleRate;
4723        int reqChannelCount = mReqChannelCount;
4724
4725        if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4726            reqSamplingRate = value;
4727            reconfig = true;
4728        }
4729        if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4730            reqFormat = (audio_format_t) value;
4731            reconfig = true;
4732        }
4733        if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4734            reqChannelCount = popcount(value);
4735            reconfig = true;
4736        }
4737        if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4738            // do not accept frame count changes if tracks are open as the track buffer
4739            // size depends on frame count and correct behavior would not be garantied
4740            // if frame count is changed after track creation
4741            if (mActiveTrack != 0) {
4742                status = INVALID_OPERATION;
4743            } else {
4744                reconfig = true;
4745            }
4746        }
4747        if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4748            // forward device change to effects that have requested to be
4749            // aware of attached audio device.
4750            for (size_t i = 0; i < mEffectChains.size(); i++) {
4751                mEffectChains[i]->setDevice_l(value);
4752            }
4753            // store input device and output device but do not forward output device to audio HAL.
4754            // Note that status is ignored by the caller for output device
4755            // (see AudioFlinger::setParameters()
4756            if (value & AUDIO_DEVICE_OUT_ALL) {
4757                mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4758                status = BAD_VALUE;
4759            } else {
4760                mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
4761                // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4762                if (mTrack != NULL) {
4763                    bool suspend = audio_is_bluetooth_sco_device(
4764                            (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
4765                    setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4766                    setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4767                }
4768            }
4769            mDevice |= (uint32_t)value;
4770        }
4771        if (status == NO_ERROR) {
4772            status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
4773            if (status == INVALID_OPERATION) {
4774               mInput->stream->common.standby(&mInput->stream->common);
4775               status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
4776            }
4777            if (reconfig) {
4778                if (status == BAD_VALUE &&
4779                    reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
4780                    reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
4781                    ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4782                    (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
4783                    (reqChannelCount < 3)) {
4784                    status = NO_ERROR;
4785                }
4786                if (status == NO_ERROR) {
4787                    readInputParameters();
4788                    sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4789                }
4790            }
4791        }
4792
4793        mNewParameters.removeAt(0);
4794
4795        mParamStatus = status;
4796        mParamCond.signal();
4797        // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4798        // already timed out waiting for the status and will never signal the condition.
4799        mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
4800    }
4801    return reconfig;
4802}
4803
4804String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4805{
4806    char *s;
4807    String8 out_s8 = String8();
4808
4809    Mutex::Autolock _l(mLock);
4810    if (initCheck() != NO_ERROR) {
4811        return out_s8;
4812    }
4813
4814    s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
4815    out_s8 = String8(s);
4816    free(s);
4817    return out_s8;
4818}
4819
4820void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4821    AudioSystem::OutputDescriptor desc;
4822    void *param2 = NULL;
4823
4824    switch (event) {
4825    case AudioSystem::INPUT_OPENED:
4826    case AudioSystem::INPUT_CONFIG_CHANGED:
4827        desc.channels = mChannelMask;
4828        desc.samplingRate = mSampleRate;
4829        desc.format = mFormat;
4830        desc.frameCount = mFrameCount;
4831        desc.latency = 0;
4832        param2 = &desc;
4833        break;
4834
4835    case AudioSystem::INPUT_CLOSED:
4836    default:
4837        break;
4838    }
4839    mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4840}
4841
4842void AudioFlinger::RecordThread::readInputParameters()
4843{
4844    delete mRsmpInBuffer;
4845    // mRsmpInBuffer is always assigned a new[] below
4846    delete mRsmpOutBuffer;
4847    mRsmpOutBuffer = NULL;
4848    delete mResampler;
4849    mResampler = NULL;
4850
4851    mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
4852    mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4853    mChannelCount = (uint16_t)popcount(mChannelMask);
4854    mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4855    mFrameSize = audio_stream_frame_size(&mInput->stream->common);
4856    mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
4857    mFrameCount = mInputBytes / mFrameSize;
4858    mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4859
4860    if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4861    {
4862        int channelCount;
4863         // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4864         // stereo to mono post process as the resampler always outputs stereo.
4865        if (mChannelCount == 1 && mReqChannelCount == 2) {
4866            channelCount = 1;
4867        } else {
4868            channelCount = 2;
4869        }
4870        mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4871        mResampler->setSampleRate(mSampleRate);
4872        mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4873        mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4874
4875        // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4876        if (mChannelCount == 1 && mReqChannelCount == 1) {
4877            mFrameCount >>= 1;
4878        }
4879
4880    }
4881    mRsmpInIndex = mFrameCount;
4882}
4883
4884unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4885{
4886    Mutex::Autolock _l(mLock);
4887    if (initCheck() != NO_ERROR) {
4888        return 0;
4889    }
4890
4891    return mInput->stream->get_input_frames_lost(mInput->stream);
4892}
4893
4894uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4895{
4896    Mutex::Autolock _l(mLock);
4897    uint32_t result = 0;
4898    if (getEffectChain_l(sessionId) != 0) {
4899        result = EFFECT_SESSION;
4900    }
4901
4902    if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4903        result |= TRACK_SESSION;
4904    }
4905
4906    return result;
4907}
4908
4909AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4910{
4911    Mutex::Autolock _l(mLock);
4912    return mTrack;
4913}
4914
4915AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
4916{
4917    Mutex::Autolock _l(mLock);
4918    return mInput;
4919}
4920
4921AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4922{
4923    Mutex::Autolock _l(mLock);
4924    AudioStreamIn *input = mInput;
4925    mInput = NULL;
4926    return input;
4927}
4928
4929// this method must always be called either with ThreadBase mLock held or inside the thread loop
4930audio_stream_t* AudioFlinger::RecordThread::stream()
4931{
4932    if (mInput == NULL) {
4933        return NULL;
4934    }
4935    return &mInput->stream->common;
4936}
4937
4938
4939// ----------------------------------------------------------------------------
4940
4941int AudioFlinger::openOutput(uint32_t *pDevices,
4942                                uint32_t *pSamplingRate,
4943                                audio_format_t *pFormat,
4944                                uint32_t *pChannels,
4945                                uint32_t *pLatencyMs,
4946                                uint32_t flags)
4947{
4948    status_t status;
4949    PlaybackThread *thread = NULL;
4950    mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4951    uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4952    audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
4953    uint32_t channels = pChannels ? *pChannels : 0;
4954    uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
4955    audio_stream_out_t *outStream;
4956    audio_hw_device_t *outHwDev;
4957
4958    ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4959            pDevices ? *pDevices : 0,
4960            samplingRate,
4961            format,
4962            channels,
4963            flags);
4964
4965    if (pDevices == NULL || *pDevices == 0) {
4966        return 0;
4967    }
4968
4969    Mutex::Autolock _l(mLock);
4970
4971    outHwDev = findSuitableHwDev_l(*pDevices);
4972    if (outHwDev == NULL)
4973        return 0;
4974
4975    status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
4976                                          &channels, &samplingRate, &outStream);
4977    ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
4978            outStream,
4979            samplingRate,
4980            format,
4981            channels,
4982            status);
4983
4984    mHardwareStatus = AUDIO_HW_IDLE;
4985    if (outStream != NULL) {
4986        AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
4987        int id = nextUniqueId();
4988
4989        if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4990            (format != AUDIO_FORMAT_PCM_16_BIT) ||
4991            (channels != AUDIO_CHANNEL_OUT_STEREO)) {
4992            thread = new DirectOutputThread(this, output, id, *pDevices);
4993            ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4994        } else {
4995            thread = new MixerThread(this, output, id, *pDevices);
4996            ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
4997        }
4998        mPlaybackThreads.add(id, thread);
4999
5000        if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5001        if (pFormat != NULL) *pFormat = format;
5002        if (pChannels != NULL) *pChannels = channels;
5003        if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
5004
5005        // notify client processes of the new output creation
5006        thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5007        return id;
5008    }
5009
5010    return 0;
5011}
5012
5013int AudioFlinger::openDuplicateOutput(int output1, int output2)
5014{
5015    Mutex::Autolock _l(mLock);
5016    MixerThread *thread1 = checkMixerThread_l(output1);
5017    MixerThread *thread2 = checkMixerThread_l(output2);
5018
5019    if (thread1 == NULL || thread2 == NULL) {
5020        ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
5021        return 0;
5022    }
5023
5024    int id = nextUniqueId();
5025    DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5026    thread->addOutputTrack(thread2);
5027    mPlaybackThreads.add(id, thread);
5028    // notify client processes of the new output creation
5029    thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5030    return id;
5031}
5032
5033status_t AudioFlinger::closeOutput(int output)
5034{
5035    // keep strong reference on the playback thread so that
5036    // it is not destroyed while exit() is executed
5037    sp <PlaybackThread> thread;
5038    {
5039        Mutex::Autolock _l(mLock);
5040        thread = checkPlaybackThread_l(output);
5041        if (thread == NULL) {
5042            return BAD_VALUE;
5043        }
5044
5045        ALOGV("closeOutput() %d", output);
5046
5047        if (thread->type() == ThreadBase::MIXER) {
5048            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5049                if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
5050                    DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5051                    dupThread->removeOutputTrack((MixerThread *)thread.get());
5052                }
5053            }
5054        }
5055        void *param2 = NULL;
5056        audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5057        mPlaybackThreads.removeItem(output);
5058    }
5059    thread->exit();
5060
5061    if (thread->type() != ThreadBase::DUPLICATING) {
5062        AudioStreamOut *out = thread->clearOutput();
5063        assert(out != NULL);
5064        // from now on thread->mOutput is NULL
5065        out->hwDev->close_output_stream(out->hwDev, out->stream);
5066        delete out;
5067    }
5068    return NO_ERROR;
5069}
5070
5071status_t AudioFlinger::suspendOutput(int output)
5072{
5073    Mutex::Autolock _l(mLock);
5074    PlaybackThread *thread = checkPlaybackThread_l(output);
5075
5076    if (thread == NULL) {
5077        return BAD_VALUE;
5078    }
5079
5080    ALOGV("suspendOutput() %d", output);
5081    thread->suspend();
5082
5083    return NO_ERROR;
5084}
5085
5086status_t AudioFlinger::restoreOutput(int output)
5087{
5088    Mutex::Autolock _l(mLock);
5089    PlaybackThread *thread = checkPlaybackThread_l(output);
5090
5091    if (thread == NULL) {
5092        return BAD_VALUE;
5093    }
5094
5095    ALOGV("restoreOutput() %d", output);
5096
5097    thread->restore();
5098
5099    return NO_ERROR;
5100}
5101
5102int AudioFlinger::openInput(uint32_t *pDevices,
5103                                uint32_t *pSamplingRate,
5104                                audio_format_t *pFormat,
5105                                uint32_t *pChannels,
5106                                audio_in_acoustics_t acoustics)
5107{
5108    status_t status;
5109    RecordThread *thread = NULL;
5110    uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5111    audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
5112    uint32_t channels = pChannels ? *pChannels : 0;
5113    uint32_t reqSamplingRate = samplingRate;
5114    audio_format_t reqFormat = format;
5115    uint32_t reqChannels = channels;
5116    audio_stream_in_t *inStream;
5117    audio_hw_device_t *inHwDev;
5118
5119    if (pDevices == NULL || *pDevices == 0) {
5120        return 0;
5121    }
5122
5123    Mutex::Autolock _l(mLock);
5124
5125    inHwDev = findSuitableHwDev_l(*pDevices);
5126    if (inHwDev == NULL)
5127        return 0;
5128
5129    status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
5130                                        &channels, &samplingRate,
5131                                        acoustics,
5132                                        &inStream);
5133    ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
5134            inStream,
5135            samplingRate,
5136            format,
5137            channels,
5138            acoustics,
5139            status);
5140
5141    // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5142    // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5143    // or stereo to mono conversions on 16 bit PCM inputs.
5144    if (inStream == NULL && status == BAD_VALUE &&
5145        reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
5146        (samplingRate <= 2 * reqSamplingRate) &&
5147        (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
5148        ALOGV("openInput() reopening with proposed sampling rate and channels");
5149        status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
5150                                            &channels, &samplingRate,
5151                                            acoustics,
5152                                            &inStream);
5153    }
5154
5155    if (inStream != NULL) {
5156        AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5157
5158        int id = nextUniqueId();
5159        // Start record thread
5160        // RecorThread require both input and output device indication to forward to audio
5161        // pre processing modules
5162        uint32_t device = (*pDevices) | primaryOutputDevice_l();
5163        thread = new RecordThread(this,
5164                                  input,
5165                                  reqSamplingRate,
5166                                  reqChannels,
5167                                  id,
5168                                  device);
5169        mRecordThreads.add(id, thread);
5170        ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
5171        if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5172        if (pFormat != NULL) *pFormat = format;
5173        if (pChannels != NULL) *pChannels = reqChannels;
5174
5175        input->stream->common.standby(&input->stream->common);
5176
5177        // notify client processes of the new input creation
5178        thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5179        return id;
5180    }
5181
5182    return 0;
5183}
5184
5185status_t AudioFlinger::closeInput(int input)
5186{
5187    // keep strong reference on the record thread so that
5188    // it is not destroyed while exit() is executed
5189    sp <RecordThread> thread;
5190    {
5191        Mutex::Autolock _l(mLock);
5192        thread = checkRecordThread_l(input);
5193        if (thread == NULL) {
5194            return BAD_VALUE;
5195        }
5196
5197        ALOGV("closeInput() %d", input);
5198        void *param2 = NULL;
5199        audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5200        mRecordThreads.removeItem(input);
5201    }
5202    thread->exit();
5203
5204    AudioStreamIn *in = thread->clearInput();
5205    assert(in != NULL);
5206    // from now on thread->mInput is NULL
5207    in->hwDev->close_input_stream(in->hwDev, in->stream);
5208    delete in;
5209
5210    return NO_ERROR;
5211}
5212
5213status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
5214{
5215    Mutex::Autolock _l(mLock);
5216    MixerThread *dstThread = checkMixerThread_l(output);
5217    if (dstThread == NULL) {
5218        ALOGW("setStreamOutput() bad output id %d", output);
5219        return BAD_VALUE;
5220    }
5221
5222    ALOGV("setStreamOutput() stream %d to output %d", stream, output);
5223    audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5224
5225    dstThread->setStreamValid(stream, true);
5226
5227    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5228        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5229        if (thread != dstThread &&
5230            thread->type() != ThreadBase::DIRECT) {
5231            MixerThread *srcThread = (MixerThread *)thread;
5232            srcThread->setStreamValid(stream, false);
5233            srcThread->invalidateTracks(stream);
5234        }
5235    }
5236
5237    return NO_ERROR;
5238}
5239
5240
5241int AudioFlinger::newAudioSessionId()
5242{
5243    return nextUniqueId();
5244}
5245
5246void AudioFlinger::acquireAudioSessionId(int audioSession)
5247{
5248    Mutex::Autolock _l(mLock);
5249    int caller = IPCThreadState::self()->getCallingPid();
5250    ALOGV("acquiring %d from %d", audioSession, caller);
5251    int num = mAudioSessionRefs.size();
5252    for (int i = 0; i< num; i++) {
5253        AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5254        if (ref->sessionid == audioSession && ref->pid == caller) {
5255            ref->cnt++;
5256            ALOGV(" incremented refcount to %d", ref->cnt);
5257            return;
5258        }
5259    }
5260    mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5261    ALOGV(" added new entry for %d", audioSession);
5262}
5263
5264void AudioFlinger::releaseAudioSessionId(int audioSession)
5265{
5266    Mutex::Autolock _l(mLock);
5267    int caller = IPCThreadState::self()->getCallingPid();
5268    ALOGV("releasing %d from %d", audioSession, caller);
5269    int num = mAudioSessionRefs.size();
5270    for (int i = 0; i< num; i++) {
5271        AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5272        if (ref->sessionid == audioSession && ref->pid == caller) {
5273            ref->cnt--;
5274            ALOGV(" decremented refcount to %d", ref->cnt);
5275            if (ref->cnt == 0) {
5276                mAudioSessionRefs.removeAt(i);
5277                delete ref;
5278                purgeStaleEffects_l();
5279            }
5280            return;
5281        }
5282    }
5283    ALOGW("session id %d not found for pid %d", audioSession, caller);
5284}
5285
5286void AudioFlinger::purgeStaleEffects_l() {
5287
5288    ALOGV("purging stale effects");
5289
5290    Vector< sp<EffectChain> > chains;
5291
5292    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5293        sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5294        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5295            sp<EffectChain> ec = t->mEffectChains[j];
5296            if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5297                chains.push(ec);
5298            }
5299        }
5300    }
5301    for (size_t i = 0; i < mRecordThreads.size(); i++) {
5302        sp<RecordThread> t = mRecordThreads.valueAt(i);
5303        for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5304            sp<EffectChain> ec = t->mEffectChains[j];
5305            chains.push(ec);
5306        }
5307    }
5308
5309    for (size_t i = 0; i < chains.size(); i++) {
5310        sp<EffectChain> ec = chains[i];
5311        int sessionid = ec->sessionId();
5312        sp<ThreadBase> t = ec->mThread.promote();
5313        if (t == 0) {
5314            continue;
5315        }
5316        size_t numsessionrefs = mAudioSessionRefs.size();
5317        bool found = false;
5318        for (size_t k = 0; k < numsessionrefs; k++) {
5319            AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5320            if (ref->sessionid == sessionid) {
5321                ALOGV(" session %d still exists for %d with %d refs",
5322                     sessionid, ref->pid, ref->cnt);
5323                found = true;
5324                break;
5325            }
5326        }
5327        if (!found) {
5328            // remove all effects from the chain
5329            while (ec->mEffects.size()) {
5330                sp<EffectModule> effect = ec->mEffects[0];
5331                effect->unPin();
5332                Mutex::Autolock _l (t->mLock);
5333                t->removeEffect_l(effect);
5334                for (size_t j = 0; j < effect->mHandles.size(); j++) {
5335                    sp<EffectHandle> handle = effect->mHandles[j].promote();
5336                    if (handle != 0) {
5337                        handle->mEffect.clear();
5338                        if (handle->mHasControl && handle->mEnabled) {
5339                            t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5340                        }
5341                    }
5342                }
5343                AudioSystem::unregisterEffect(effect->id());
5344            }
5345        }
5346    }
5347    return;
5348}
5349
5350// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5351AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5352{
5353    PlaybackThread *thread = NULL;
5354    if (mPlaybackThreads.indexOfKey(output) >= 0) {
5355        thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5356    }
5357    return thread;
5358}
5359
5360// checkMixerThread_l() must be called with AudioFlinger::mLock held
5361AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5362{
5363    PlaybackThread *thread = checkPlaybackThread_l(output);
5364    if (thread != NULL) {
5365        if (thread->type() == ThreadBase::DIRECT) {
5366            thread = NULL;
5367        }
5368    }
5369    return (MixerThread *)thread;
5370}
5371
5372// checkRecordThread_l() must be called with AudioFlinger::mLock held
5373AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5374{
5375    RecordThread *thread = NULL;
5376    if (mRecordThreads.indexOfKey(input) >= 0) {
5377        thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5378    }
5379    return thread;
5380}
5381
5382uint32_t AudioFlinger::nextUniqueId()
5383{
5384    return android_atomic_inc(&mNextUniqueId);
5385}
5386
5387AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5388{
5389    for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5390        PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5391        AudioStreamOut *output = thread->getOutput();
5392        if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
5393            return thread;
5394        }
5395    }
5396    return NULL;
5397}
5398
5399uint32_t AudioFlinger::primaryOutputDevice_l()
5400{
5401    PlaybackThread *thread = primaryPlaybackThread_l();
5402
5403    if (thread == NULL) {
5404        return 0;
5405    }
5406
5407    return thread->device();
5408}
5409
5410
5411// ----------------------------------------------------------------------------
5412//  Effect management
5413// ----------------------------------------------------------------------------
5414
5415
5416status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
5417{
5418    Mutex::Autolock _l(mLock);
5419    return EffectQueryNumberEffects(numEffects);
5420}
5421
5422status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
5423{
5424    Mutex::Autolock _l(mLock);
5425    return EffectQueryEffect(index, descriptor);
5426}
5427
5428status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid,
5429        effect_descriptor_t *descriptor) const
5430{
5431    Mutex::Autolock _l(mLock);
5432    return EffectGetDescriptor(pUuid, descriptor);
5433}
5434
5435
5436sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5437        effect_descriptor_t *pDesc,
5438        const sp<IEffectClient>& effectClient,
5439        int32_t priority,
5440        int io,
5441        int sessionId,
5442        status_t *status,
5443        int *id,
5444        int *enabled)
5445{
5446    status_t lStatus = NO_ERROR;
5447    sp<EffectHandle> handle;
5448    effect_descriptor_t desc;
5449    sp<Client> client;
5450    wp<Client> wclient;
5451
5452    ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
5453            pid, effectClient.get(), priority, sessionId, io);
5454
5455    if (pDesc == NULL) {
5456        lStatus = BAD_VALUE;
5457        goto Exit;
5458    }
5459
5460    // check audio settings permission for global effects
5461    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
5462        lStatus = PERMISSION_DENIED;
5463        goto Exit;
5464    }
5465
5466    // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
5467    // that can only be created by audio policy manager (running in same process)
5468    if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
5469        lStatus = PERMISSION_DENIED;
5470        goto Exit;
5471    }
5472
5473    if (io == 0) {
5474        if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
5475            // output must be specified by AudioPolicyManager when using session
5476            // AUDIO_SESSION_OUTPUT_STAGE
5477            lStatus = BAD_VALUE;
5478            goto Exit;
5479        } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
5480            // if the output returned by getOutputForEffect() is removed before we lock the
5481            // mutex below, the call to checkPlaybackThread_l(io) below will detect it
5482            // and we will exit safely
5483            io = AudioSystem::getOutputForEffect(&desc);
5484        }
5485    }
5486
5487    {
5488        Mutex::Autolock _l(mLock);
5489
5490
5491        if (!EffectIsNullUuid(&pDesc->uuid)) {
5492            // if uuid is specified, request effect descriptor
5493            lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5494            if (lStatus < 0) {
5495                ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5496                goto Exit;
5497            }
5498        } else {
5499            // if uuid is not specified, look for an available implementation
5500            // of the required type in effect factory
5501            if (EffectIsNullUuid(&pDesc->type)) {
5502                ALOGW("createEffect() no effect type");
5503                lStatus = BAD_VALUE;
5504                goto Exit;
5505            }
5506            uint32_t numEffects = 0;
5507            effect_descriptor_t d;
5508            d.flags = 0; // prevent compiler warning
5509            bool found = false;
5510
5511            lStatus = EffectQueryNumberEffects(&numEffects);
5512            if (lStatus < 0) {
5513                ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5514                goto Exit;
5515            }
5516            for (uint32_t i = 0; i < numEffects; i++) {
5517                lStatus = EffectQueryEffect(i, &desc);
5518                if (lStatus < 0) {
5519                    ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5520                    continue;
5521                }
5522                if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5523                    // If matching type found save effect descriptor. If the session is
5524                    // 0 and the effect is not auxiliary, continue enumeration in case
5525                    // an auxiliary version of this effect type is available
5526                    found = true;
5527                    memcpy(&d, &desc, sizeof(effect_descriptor_t));
5528                    if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
5529                            (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5530                        break;
5531                    }
5532                }
5533            }
5534            if (!found) {
5535                lStatus = BAD_VALUE;
5536                ALOGW("createEffect() effect not found");
5537                goto Exit;
5538            }
5539            // For same effect type, chose auxiliary version over insert version if
5540            // connect to output mix (Compliance to OpenSL ES)
5541            if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
5542                    (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5543                memcpy(&desc, &d, sizeof(effect_descriptor_t));
5544            }
5545        }
5546
5547        // Do not allow auxiliary effects on a session different from 0 (output mix)
5548        if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
5549             (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5550            lStatus = INVALID_OPERATION;
5551            goto Exit;
5552        }
5553
5554        // check recording permission for visualizer
5555        if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5556            !recordingAllowed()) {
5557            lStatus = PERMISSION_DENIED;
5558            goto Exit;
5559        }
5560
5561        // return effect descriptor
5562        memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5563
5564        // If output is not specified try to find a matching audio session ID in one of the
5565        // output threads.
5566        // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5567        // because of code checking output when entering the function.
5568        // Note: io is never 0 when creating an effect on an input
5569        if (io == 0) {
5570             // look for the thread where the specified audio session is present
5571            for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5572                if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5573                    io = mPlaybackThreads.keyAt(i);
5574                    break;
5575                }
5576            }
5577            if (io == 0) {
5578               for (size_t i = 0; i < mRecordThreads.size(); i++) {
5579                   if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5580                       io = mRecordThreads.keyAt(i);
5581                       break;
5582                   }
5583               }
5584            }
5585            // If no output thread contains the requested session ID, default to
5586            // first output. The effect chain will be moved to the correct output
5587            // thread when a track with the same session ID is created
5588            if (io == 0 && mPlaybackThreads.size()) {
5589                io = mPlaybackThreads.keyAt(0);
5590            }
5591            ALOGV("createEffect() got io %d for effect %s", io, desc.name);
5592        }
5593        ThreadBase *thread = checkRecordThread_l(io);
5594        if (thread == NULL) {
5595            thread = checkPlaybackThread_l(io);
5596            if (thread == NULL) {
5597                ALOGE("createEffect() unknown output thread");
5598                lStatus = BAD_VALUE;
5599                goto Exit;
5600            }
5601        }
5602
5603        wclient = mClients.valueFor(pid);
5604
5605        if (wclient != NULL) {
5606            client = wclient.promote();
5607        } else {
5608            client = new Client(this, pid);
5609            mClients.add(pid, client);
5610        }
5611
5612        // create effect on selected output thread
5613        handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5614                &desc, enabled, &lStatus);
5615        if (handle != 0 && id != NULL) {
5616            *id = handle->id();
5617        }
5618    }
5619
5620Exit:
5621    if(status) {
5622        *status = lStatus;
5623    }
5624    return handle;
5625}
5626
5627status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
5628{
5629    ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
5630            sessionId, srcOutput, dstOutput);
5631    Mutex::Autolock _l(mLock);
5632    if (srcOutput == dstOutput) {
5633        ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
5634        return NO_ERROR;
5635    }
5636    PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5637    if (srcThread == NULL) {
5638        ALOGW("moveEffects() bad srcOutput %d", srcOutput);
5639        return BAD_VALUE;
5640    }
5641    PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5642    if (dstThread == NULL) {
5643        ALOGW("moveEffects() bad dstOutput %d", dstOutput);
5644        return BAD_VALUE;
5645    }
5646
5647    Mutex::Autolock _dl(dstThread->mLock);
5648    Mutex::Autolock _sl(srcThread->mLock);
5649    moveEffectChain_l(sessionId, srcThread, dstThread, false);
5650
5651    return NO_ERROR;
5652}
5653
5654// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
5655status_t AudioFlinger::moveEffectChain_l(int sessionId,
5656                                   AudioFlinger::PlaybackThread *srcThread,
5657                                   AudioFlinger::PlaybackThread *dstThread,
5658                                   bool reRegister)
5659{
5660    ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
5661            sessionId, srcThread, dstThread);
5662
5663    sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
5664    if (chain == 0) {
5665        ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
5666                sessionId, srcThread);
5667        return INVALID_OPERATION;
5668    }
5669
5670    // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
5671    // so that a new chain is created with correct parameters when first effect is added. This is
5672    // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
5673    // removed.
5674    srcThread->removeEffectChain_l(chain);
5675
5676    // transfer all effects one by one so that new effect chain is created on new thread with
5677    // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
5678    int dstOutput = dstThread->id();
5679    sp<EffectChain> dstChain;
5680    uint32_t strategy = 0; // prevent compiler warning
5681    sp<EffectModule> effect = chain->getEffectFromId_l(0);
5682    while (effect != 0) {
5683        srcThread->removeEffect_l(effect);
5684        dstThread->addEffect_l(effect);
5685        // removeEffect_l() has stopped the effect if it was active so it must be restarted
5686        if (effect->state() == EffectModule::ACTIVE ||
5687                effect->state() == EffectModule::STOPPING) {
5688            effect->start();
5689        }
5690        // if the move request is not received from audio policy manager, the effect must be
5691        // re-registered with the new strategy and output
5692        if (dstChain == 0) {
5693            dstChain = effect->chain().promote();
5694            if (dstChain == 0) {
5695                ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5696                srcThread->addEffect_l(effect);
5697                return NO_INIT;
5698            }
5699            strategy = dstChain->strategy();
5700        }
5701        if (reRegister) {
5702            AudioSystem::unregisterEffect(effect->id());
5703            AudioSystem::registerEffect(&effect->desc(),
5704                                        dstOutput,
5705                                        strategy,
5706                                        sessionId,
5707                                        effect->id());
5708        }
5709        effect = chain->getEffectFromId_l(0);
5710    }
5711
5712    return NO_ERROR;
5713}
5714
5715
5716// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
5717sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
5718        const sp<AudioFlinger::Client>& client,
5719        const sp<IEffectClient>& effectClient,
5720        int32_t priority,
5721        int sessionId,
5722        effect_descriptor_t *desc,
5723        int *enabled,
5724        status_t *status
5725        )
5726{
5727    sp<EffectModule> effect;
5728    sp<EffectHandle> handle;
5729    status_t lStatus;
5730    sp<EffectChain> chain;
5731    bool chainCreated = false;
5732    bool effectCreated = false;
5733    bool effectRegistered = false;
5734
5735    lStatus = initCheck();
5736    if (lStatus != NO_ERROR) {
5737        ALOGW("createEffect_l() Audio driver not initialized.");
5738        goto Exit;
5739    }
5740
5741    // Do not allow effects with session ID 0 on direct output or duplicating threads
5742    // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
5743    if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
5744        ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5745                desc->name, sessionId);
5746        lStatus = BAD_VALUE;
5747        goto Exit;
5748    }
5749    // Only Pre processor effects are allowed on input threads and only on input threads
5750    if ((mType == RECORD &&
5751            (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5752            (mType != RECORD &&
5753                    (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5754        ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5755                desc->name, desc->flags, mType);
5756        lStatus = BAD_VALUE;
5757        goto Exit;
5758    }
5759
5760    ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
5761
5762    { // scope for mLock
5763        Mutex::Autolock _l(mLock);
5764
5765        // check for existing effect chain with the requested audio session
5766        chain = getEffectChain_l(sessionId);
5767        if (chain == 0) {
5768            // create a new chain for this session
5769            ALOGV("createEffect_l() new effect chain for session %d", sessionId);
5770            chain = new EffectChain(this, sessionId);
5771            addEffectChain_l(chain);
5772            chain->setStrategy(getStrategyForSession_l(sessionId));
5773            chainCreated = true;
5774        } else {
5775            effect = chain->getEffectFromDesc_l(desc);
5776        }
5777
5778        ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
5779
5780        if (effect == 0) {
5781            int id = mAudioFlinger->nextUniqueId();
5782            // Check CPU and memory usage
5783            lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
5784            if (lStatus != NO_ERROR) {
5785                goto Exit;
5786            }
5787            effectRegistered = true;
5788            // create a new effect module if none present in the chain
5789            effect = new EffectModule(this, chain, desc, id, sessionId);
5790            lStatus = effect->status();
5791            if (lStatus != NO_ERROR) {
5792                goto Exit;
5793            }
5794            lStatus = chain->addEffect_l(effect);
5795            if (lStatus != NO_ERROR) {
5796                goto Exit;
5797            }
5798            effectCreated = true;
5799
5800            effect->setDevice(mDevice);
5801            effect->setMode(mAudioFlinger->getMode());
5802        }
5803        // create effect handle and connect it to effect module
5804        handle = new EffectHandle(effect, client, effectClient, priority);
5805        lStatus = effect->addHandle(handle);
5806        if (enabled != NULL) {
5807            *enabled = (int)effect->isEnabled();
5808        }
5809    }
5810
5811Exit:
5812    if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
5813        Mutex::Autolock _l(mLock);
5814        if (effectCreated) {
5815            chain->removeEffect_l(effect);
5816        }
5817        if (effectRegistered) {
5818            AudioSystem::unregisterEffect(effect->id());
5819        }
5820        if (chainCreated) {
5821            removeEffectChain_l(chain);
5822        }
5823        handle.clear();
5824    }
5825
5826    if(status) {
5827        *status = lStatus;
5828    }
5829    return handle;
5830}
5831
5832sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5833{
5834    sp<EffectModule> effect;
5835
5836    sp<EffectChain> chain = getEffectChain_l(sessionId);
5837    if (chain != 0) {
5838        effect = chain->getEffectFromId_l(effectId);
5839    }
5840    return effect;
5841}
5842
5843// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5844// PlaybackThread::mLock held
5845status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
5846{
5847    // check for existing effect chain with the requested audio session
5848    int sessionId = effect->sessionId();
5849    sp<EffectChain> chain = getEffectChain_l(sessionId);
5850    bool chainCreated = false;
5851
5852    if (chain == 0) {
5853        // create a new chain for this session
5854        ALOGV("addEffect_l() new effect chain for session %d", sessionId);
5855        chain = new EffectChain(this, sessionId);
5856        addEffectChain_l(chain);
5857        chain->setStrategy(getStrategyForSession_l(sessionId));
5858        chainCreated = true;
5859    }
5860    ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5861
5862    if (chain->getEffectFromId_l(effect->id()) != 0) {
5863        ALOGW("addEffect_l() %p effect %s already present in chain %p",
5864                this, effect->desc().name, chain.get());
5865        return BAD_VALUE;
5866    }
5867
5868    status_t status = chain->addEffect_l(effect);
5869    if (status != NO_ERROR) {
5870        if (chainCreated) {
5871            removeEffectChain_l(chain);
5872        }
5873        return status;
5874    }
5875
5876    effect->setDevice(mDevice);
5877    effect->setMode(mAudioFlinger->getMode());
5878    return NO_ERROR;
5879}
5880
5881void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
5882
5883    ALOGV("removeEffect_l() %p effect %p", this, effect.get());
5884    effect_descriptor_t desc = effect->desc();
5885    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5886        detachAuxEffect_l(effect->id());
5887    }
5888
5889    sp<EffectChain> chain = effect->chain().promote();
5890    if (chain != 0) {
5891        // remove effect chain if removing last effect
5892        if (chain->removeEffect_l(effect) == 0) {
5893            removeEffectChain_l(chain);
5894        }
5895    } else {
5896        ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5897    }
5898}
5899
5900void AudioFlinger::ThreadBase::lockEffectChains_l(
5901        Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5902{
5903    effectChains = mEffectChains;
5904    for (size_t i = 0; i < mEffectChains.size(); i++) {
5905        mEffectChains[i]->lock();
5906    }
5907}
5908
5909void AudioFlinger::ThreadBase::unlockEffectChains(
5910        Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5911{
5912    for (size_t i = 0; i < effectChains.size(); i++) {
5913        effectChains[i]->unlock();
5914    }
5915}
5916
5917sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5918{
5919    Mutex::Autolock _l(mLock);
5920    return getEffectChain_l(sessionId);
5921}
5922
5923sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5924{
5925    sp<EffectChain> chain;
5926
5927    size_t size = mEffectChains.size();
5928    for (size_t i = 0; i < size; i++) {
5929        if (mEffectChains[i]->sessionId() == sessionId) {
5930            chain = mEffectChains[i];
5931            break;
5932        }
5933    }
5934    return chain;
5935}
5936
5937void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
5938{
5939    Mutex::Autolock _l(mLock);
5940    size_t size = mEffectChains.size();
5941    for (size_t i = 0; i < size; i++) {
5942        mEffectChains[i]->setMode_l(mode);
5943    }
5944}
5945
5946void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
5947                                                    const wp<EffectHandle>& handle,
5948                                                    bool unpiniflast) {
5949
5950    Mutex::Autolock _l(mLock);
5951    ALOGV("disconnectEffect() %p effect %p", this, effect.get());
5952    // delete the effect module if removing last handle on it
5953    if (effect->removeHandle(handle) == 0) {
5954        if (!effect->isPinned() || unpiniflast) {
5955            removeEffect_l(effect);
5956            AudioSystem::unregisterEffect(effect->id());
5957        }
5958    }
5959}
5960
5961status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5962{
5963    int session = chain->sessionId();
5964    int16_t *buffer = mMixBuffer;
5965    bool ownsBuffer = false;
5966
5967    ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5968    if (session > 0) {
5969        // Only one effect chain can be present in direct output thread and it uses
5970        // the mix buffer as input
5971        if (mType != DIRECT) {
5972            size_t numSamples = mFrameCount * mChannelCount;
5973            buffer = new int16_t[numSamples];
5974            memset(buffer, 0, numSamples * sizeof(int16_t));
5975            ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5976            ownsBuffer = true;
5977        }
5978
5979        // Attach all tracks with same session ID to this chain.
5980        for (size_t i = 0; i < mTracks.size(); ++i) {
5981            sp<Track> track = mTracks[i];
5982            if (session == track->sessionId()) {
5983                ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5984                track->setMainBuffer(buffer);
5985                chain->incTrackCnt();
5986            }
5987        }
5988
5989        // indicate all active tracks in the chain
5990        for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5991            sp<Track> track = mActiveTracks[i].promote();
5992            if (track == 0) continue;
5993            if (session == track->sessionId()) {
5994                ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
5995                chain->incActiveTrackCnt();
5996            }
5997        }
5998    }
5999
6000    chain->setInBuffer(buffer, ownsBuffer);
6001    chain->setOutBuffer(mMixBuffer);
6002    // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
6003    // chains list in order to be processed last as it contains output stage effects
6004    // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6005    // session AUDIO_SESSION_OUTPUT_STAGE to be processed
6006    // after track specific effects and before output stage
6007    // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6008    // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
6009    // Effect chain for other sessions are inserted at beginning of effect
6010    // chains list to be processed before output mix effects. Relative order between other
6011    // sessions is not important
6012    size_t size = mEffectChains.size();
6013    size_t i = 0;
6014    for (i = 0; i < size; i++) {
6015        if (mEffectChains[i]->sessionId() < session) break;
6016    }
6017    mEffectChains.insertAt(chain, i);
6018    checkSuspendOnAddEffectChain_l(chain);
6019
6020    return NO_ERROR;
6021}
6022
6023size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6024{
6025    int session = chain->sessionId();
6026
6027    ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
6028
6029    for (size_t i = 0; i < mEffectChains.size(); i++) {
6030        if (chain == mEffectChains[i]) {
6031            mEffectChains.removeAt(i);
6032            // detach all active tracks from the chain
6033            for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6034                sp<Track> track = mActiveTracks[i].promote();
6035                if (track == 0) continue;
6036                if (session == track->sessionId()) {
6037                    ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
6038                            chain.get(), session);
6039                    chain->decActiveTrackCnt();
6040                }
6041            }
6042
6043            // detach all tracks with same session ID from this chain
6044            for (size_t i = 0; i < mTracks.size(); ++i) {
6045                sp<Track> track = mTracks[i];
6046                if (session == track->sessionId()) {
6047                    track->setMainBuffer(mMixBuffer);
6048                    chain->decTrackCnt();
6049                }
6050            }
6051            break;
6052        }
6053    }
6054    return mEffectChains.size();
6055}
6056
6057status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6058        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
6059{
6060    Mutex::Autolock _l(mLock);
6061    return attachAuxEffect_l(track, EffectId);
6062}
6063
6064status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6065        const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
6066{
6067    status_t status = NO_ERROR;
6068
6069    if (EffectId == 0) {
6070        track->setAuxBuffer(0, NULL);
6071    } else {
6072        // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6073        sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
6074        if (effect != 0) {
6075            if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6076                track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6077            } else {
6078                status = INVALID_OPERATION;
6079            }
6080        } else {
6081            status = BAD_VALUE;
6082        }
6083    }
6084    return status;
6085}
6086
6087void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6088{
6089     for (size_t i = 0; i < mTracks.size(); ++i) {
6090        sp<Track> track = mTracks[i];
6091        if (track->auxEffectId() == effectId) {
6092            attachAuxEffect_l(track, 0);
6093        }
6094    }
6095}
6096
6097status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6098{
6099    // only one chain per input thread
6100    if (mEffectChains.size() != 0) {
6101        return INVALID_OPERATION;
6102    }
6103    ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6104
6105    chain->setInBuffer(NULL);
6106    chain->setOutBuffer(NULL);
6107
6108    checkSuspendOnAddEffectChain_l(chain);
6109
6110    mEffectChains.add(chain);
6111
6112    return NO_ERROR;
6113}
6114
6115size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6116{
6117    ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6118    ALOGW_IF(mEffectChains.size() != 1,
6119            "removeEffectChain_l() %p invalid chain size %d on thread %p",
6120            chain.get(), mEffectChains.size(), this);
6121    if (mEffectChains.size() == 1) {
6122        mEffectChains.removeAt(0);
6123    }
6124    return 0;
6125}
6126
6127// ----------------------------------------------------------------------------
6128//  EffectModule implementation
6129// ----------------------------------------------------------------------------
6130
6131#undef LOG_TAG
6132#define LOG_TAG "AudioFlinger::EffectModule"
6133
6134AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6135                                        const wp<AudioFlinger::EffectChain>& chain,
6136                                        effect_descriptor_t *desc,
6137                                        int id,
6138                                        int sessionId)
6139    : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
6140      mStatus(NO_INIT), mState(IDLE), mSuspended(false)
6141{
6142    ALOGV("Constructor %p", this);
6143    int lStatus;
6144    sp<ThreadBase> thread = mThread.promote();
6145    if (thread == 0) {
6146        return;
6147    }
6148
6149    memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6150
6151    // create effect engine from effect factory
6152    mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
6153
6154    if (mStatus != NO_ERROR) {
6155        return;
6156    }
6157    lStatus = init();
6158    if (lStatus < 0) {
6159        mStatus = lStatus;
6160        goto Error;
6161    }
6162
6163    if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6164        mPinned = true;
6165    }
6166    ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
6167    return;
6168Error:
6169    EffectRelease(mEffectInterface);
6170    mEffectInterface = NULL;
6171    ALOGV("Constructor Error %d", mStatus);
6172}
6173
6174AudioFlinger::EffectModule::~EffectModule()
6175{
6176    ALOGV("Destructor %p", this);
6177    if (mEffectInterface != NULL) {
6178        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6179                (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6180            sp<ThreadBase> thread = mThread.promote();
6181            if (thread != 0) {
6182                audio_stream_t *stream = thread->stream();
6183                if (stream != NULL) {
6184                    stream->remove_audio_effect(stream, mEffectInterface);
6185                }
6186            }
6187        }
6188        // release effect engine
6189        EffectRelease(mEffectInterface);
6190    }
6191}
6192
6193status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
6194{
6195    status_t status;
6196
6197    Mutex::Autolock _l(mLock);
6198    // First handle in mHandles has highest priority and controls the effect module
6199    int priority = handle->priority();
6200    size_t size = mHandles.size();
6201    sp<EffectHandle> h;
6202    size_t i;
6203    for (i = 0; i < size; i++) {
6204        h = mHandles[i].promote();
6205        if (h == 0) continue;
6206        if (h->priority() <= priority) break;
6207    }
6208    // if inserted in first place, move effect control from previous owner to this handle
6209    if (i == 0) {
6210        bool enabled = false;
6211        if (h != 0) {
6212            enabled = h->enabled();
6213            h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
6214        }
6215        handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
6216        status = NO_ERROR;
6217    } else {
6218        status = ALREADY_EXISTS;
6219    }
6220    ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
6221    mHandles.insertAt(handle, i);
6222    return status;
6223}
6224
6225size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6226{
6227    Mutex::Autolock _l(mLock);
6228    size_t size = mHandles.size();
6229    size_t i;
6230    for (i = 0; i < size; i++) {
6231        if (mHandles[i] == handle) break;
6232    }
6233    if (i == size) {
6234        return size;
6235    }
6236    ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
6237
6238    bool enabled = false;
6239    EffectHandle *hdl = handle.unsafe_get();
6240    if (hdl != NULL) {
6241        ALOGV("removeHandle() unsafe_get OK");
6242        enabled = hdl->enabled();
6243    }
6244    mHandles.removeAt(i);
6245    size = mHandles.size();
6246    // if removed from first place, move effect control from this handle to next in line
6247    if (i == 0 && size != 0) {
6248        sp<EffectHandle> h = mHandles[0].promote();
6249        if (h != 0) {
6250            h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
6251        }
6252    }
6253
6254    // Prevent calls to process() and other functions on effect interface from now on.
6255    // The effect engine will be released by the destructor when the last strong reference on
6256    // this object is released which can happen after next process is called.
6257    if (size == 0 && !mPinned) {
6258        mState = DESTROYED;
6259    }
6260
6261    return size;
6262}
6263
6264sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6265{
6266    Mutex::Autolock _l(mLock);
6267    sp<EffectHandle> handle;
6268    if (mHandles.size() != 0) {
6269        handle = mHandles[0].promote();
6270    }
6271    return handle;
6272}
6273
6274void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
6275{
6276    ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
6277    // keep a strong reference on this EffectModule to avoid calling the
6278    // destructor before we exit
6279    sp<EffectModule> keep(this);
6280    {
6281        sp<ThreadBase> thread = mThread.promote();
6282        if (thread != 0) {
6283            thread->disconnectEffect(keep, handle, unpiniflast);
6284        }
6285    }
6286}
6287
6288void AudioFlinger::EffectModule::updateState() {
6289    Mutex::Autolock _l(mLock);
6290
6291    switch (mState) {
6292    case RESTART:
6293        reset_l();
6294        // FALL THROUGH
6295
6296    case STARTING:
6297        // clear auxiliary effect input buffer for next accumulation
6298        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6299            memset(mConfig.inputCfg.buffer.raw,
6300                   0,
6301                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6302        }
6303        start_l();
6304        mState = ACTIVE;
6305        break;
6306    case STOPPING:
6307        stop_l();
6308        mDisableWaitCnt = mMaxDisableWaitCnt;
6309        mState = STOPPED;
6310        break;
6311    case STOPPED:
6312        // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6313        // turn off sequence.
6314        if (--mDisableWaitCnt == 0) {
6315            reset_l();
6316            mState = IDLE;
6317        }
6318        break;
6319    default: //IDLE , ACTIVE, DESTROYED
6320        break;
6321    }
6322}
6323
6324void AudioFlinger::EffectModule::process()
6325{
6326    Mutex::Autolock _l(mLock);
6327
6328    if (mState == DESTROYED || mEffectInterface == NULL ||
6329            mConfig.inputCfg.buffer.raw == NULL ||
6330            mConfig.outputCfg.buffer.raw == NULL) {
6331        return;
6332    }
6333
6334    if (isProcessEnabled()) {
6335        // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6336        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6337            ditherAndClamp(mConfig.inputCfg.buffer.s32,
6338                                        mConfig.inputCfg.buffer.s32,
6339                                        mConfig.inputCfg.buffer.frameCount/2);
6340        }
6341
6342        // do the actual processing in the effect engine
6343        int ret = (*mEffectInterface)->process(mEffectInterface,
6344                                               &mConfig.inputCfg.buffer,
6345                                               &mConfig.outputCfg.buffer);
6346
6347        // force transition to IDLE state when engine is ready
6348        if (mState == STOPPED && ret == -ENODATA) {
6349            mDisableWaitCnt = 1;
6350        }
6351
6352        // clear auxiliary effect input buffer for next accumulation
6353        if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6354            memset(mConfig.inputCfg.buffer.raw, 0,
6355                   mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6356        }
6357    } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
6358                mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6359        // If an insert effect is idle and input buffer is different from output buffer,
6360        // accumulate input onto output
6361        sp<EffectChain> chain = mChain.promote();
6362        if (chain != 0 && chain->activeTrackCnt() != 0) {
6363            size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2;  //always stereo here
6364            int16_t *in = mConfig.inputCfg.buffer.s16;
6365            int16_t *out = mConfig.outputCfg.buffer.s16;
6366            for (size_t i = 0; i < frameCnt; i++) {
6367                out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
6368            }
6369        }
6370    }
6371}
6372
6373void AudioFlinger::EffectModule::reset_l()
6374{
6375    if (mEffectInterface == NULL) {
6376        return;
6377    }
6378    (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6379}
6380
6381status_t AudioFlinger::EffectModule::configure()
6382{
6383    uint32_t channels;
6384    if (mEffectInterface == NULL) {
6385        return NO_INIT;
6386    }
6387
6388    sp<ThreadBase> thread = mThread.promote();
6389    if (thread == 0) {
6390        return DEAD_OBJECT;
6391    }
6392
6393    // TODO: handle configuration of effects replacing track process
6394    if (thread->channelCount() == 1) {
6395        channels = AUDIO_CHANNEL_OUT_MONO;
6396    } else {
6397        channels = AUDIO_CHANNEL_OUT_STEREO;
6398    }
6399
6400    if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6401        mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
6402    } else {
6403        mConfig.inputCfg.channels = channels;
6404    }
6405    mConfig.outputCfg.channels = channels;
6406    mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6407    mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6408    mConfig.inputCfg.samplingRate = thread->sampleRate();
6409    mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6410    mConfig.inputCfg.bufferProvider.cookie = NULL;
6411    mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6412    mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6413    mConfig.outputCfg.bufferProvider.cookie = NULL;
6414    mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6415    mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6416    mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6417    // Insert effect:
6418    // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
6419    // always overwrites output buffer: input buffer == output buffer
6420    // - in other sessions:
6421    //      last effect in the chain accumulates in output buffer: input buffer != output buffer
6422    //      other effect: overwrites output buffer: input buffer == output buffer
6423    // Auxiliary effect:
6424    //      accumulates in output buffer: input buffer != output buffer
6425    // Therefore: accumulate <=> input buffer != output buffer
6426    if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6427        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6428    } else {
6429        mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6430    }
6431    mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6432    mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6433    mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6434    mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6435
6436    ALOGV("configure() %p thread %p buffer %p framecount %d",
6437            this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6438
6439    status_t cmdStatus;
6440    uint32_t size = sizeof(int);
6441    status_t status = (*mEffectInterface)->command(mEffectInterface,
6442                                                   EFFECT_CMD_SET_CONFIG,
6443                                                   sizeof(effect_config_t),
6444                                                   &mConfig,
6445                                                   &size,
6446                                                   &cmdStatus);
6447    if (status == 0) {
6448        status = cmdStatus;
6449    }
6450
6451    mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6452            (1000 * mConfig.outputCfg.buffer.frameCount);
6453
6454    return status;
6455}
6456
6457status_t AudioFlinger::EffectModule::init()
6458{
6459    Mutex::Autolock _l(mLock);
6460    if (mEffectInterface == NULL) {
6461        return NO_INIT;
6462    }
6463    status_t cmdStatus;
6464    uint32_t size = sizeof(status_t);
6465    status_t status = (*mEffectInterface)->command(mEffectInterface,
6466                                                   EFFECT_CMD_INIT,
6467                                                   0,
6468                                                   NULL,
6469                                                   &size,
6470                                                   &cmdStatus);
6471    if (status == 0) {
6472        status = cmdStatus;
6473    }
6474    return status;
6475}
6476
6477status_t AudioFlinger::EffectModule::start()
6478{
6479    Mutex::Autolock _l(mLock);
6480    return start_l();
6481}
6482
6483status_t AudioFlinger::EffectModule::start_l()
6484{
6485    if (mEffectInterface == NULL) {
6486        return NO_INIT;
6487    }
6488    status_t cmdStatus;
6489    uint32_t size = sizeof(status_t);
6490    status_t status = (*mEffectInterface)->command(mEffectInterface,
6491                                                   EFFECT_CMD_ENABLE,
6492                                                   0,
6493                                                   NULL,
6494                                                   &size,
6495                                                   &cmdStatus);
6496    if (status == 0) {
6497        status = cmdStatus;
6498    }
6499    if (status == 0 &&
6500            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6501             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6502        sp<ThreadBase> thread = mThread.promote();
6503        if (thread != 0) {
6504            audio_stream_t *stream = thread->stream();
6505            if (stream != NULL) {
6506                stream->add_audio_effect(stream, mEffectInterface);
6507            }
6508        }
6509    }
6510    return status;
6511}
6512
6513status_t AudioFlinger::EffectModule::stop()
6514{
6515    Mutex::Autolock _l(mLock);
6516    return stop_l();
6517}
6518
6519status_t AudioFlinger::EffectModule::stop_l()
6520{
6521    if (mEffectInterface == NULL) {
6522        return NO_INIT;
6523    }
6524    status_t cmdStatus;
6525    uint32_t size = sizeof(status_t);
6526    status_t status = (*mEffectInterface)->command(mEffectInterface,
6527                                                   EFFECT_CMD_DISABLE,
6528                                                   0,
6529                                                   NULL,
6530                                                   &size,
6531                                                   &cmdStatus);
6532    if (status == 0) {
6533        status = cmdStatus;
6534    }
6535    if (status == 0 &&
6536            ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6537             (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6538        sp<ThreadBase> thread = mThread.promote();
6539        if (thread != 0) {
6540            audio_stream_t *stream = thread->stream();
6541            if (stream != NULL) {
6542                stream->remove_audio_effect(stream, mEffectInterface);
6543            }
6544        }
6545    }
6546    return status;
6547}
6548
6549status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6550                                             uint32_t cmdSize,
6551                                             void *pCmdData,
6552                                             uint32_t *replySize,
6553                                             void *pReplyData)
6554{
6555    Mutex::Autolock _l(mLock);
6556//    ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
6557
6558    if (mState == DESTROYED || mEffectInterface == NULL) {
6559        return NO_INIT;
6560    }
6561    status_t status = (*mEffectInterface)->command(mEffectInterface,
6562                                                   cmdCode,
6563                                                   cmdSize,
6564                                                   pCmdData,
6565                                                   replySize,
6566                                                   pReplyData);
6567    if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
6568        uint32_t size = (replySize == NULL) ? 0 : *replySize;
6569        for (size_t i = 1; i < mHandles.size(); i++) {
6570            sp<EffectHandle> h = mHandles[i].promote();
6571            if (h != 0) {
6572                h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6573            }
6574        }
6575    }
6576    return status;
6577}
6578
6579status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6580{
6581
6582    Mutex::Autolock _l(mLock);
6583    ALOGV("setEnabled %p enabled %d", this, enabled);
6584
6585    if (enabled != isEnabled()) {
6586        status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6587        if (enabled && status != NO_ERROR) {
6588            return status;
6589        }
6590
6591        switch (mState) {
6592        // going from disabled to enabled
6593        case IDLE:
6594            mState = STARTING;
6595            break;
6596        case STOPPED:
6597            mState = RESTART;
6598            break;
6599        case STOPPING:
6600            mState = ACTIVE;
6601            break;
6602
6603        // going from enabled to disabled
6604        case RESTART:
6605            mState = STOPPED;
6606            break;
6607        case STARTING:
6608            mState = IDLE;
6609            break;
6610        case ACTIVE:
6611            mState = STOPPING;
6612            break;
6613        case DESTROYED:
6614            return NO_ERROR; // simply ignore as we are being destroyed
6615        }
6616        for (size_t i = 1; i < mHandles.size(); i++) {
6617            sp<EffectHandle> h = mHandles[i].promote();
6618            if (h != 0) {
6619                h->setEnabled(enabled);
6620            }
6621        }
6622    }
6623    return NO_ERROR;
6624}
6625
6626bool AudioFlinger::EffectModule::isEnabled()
6627{
6628    switch (mState) {
6629    case RESTART:
6630    case STARTING:
6631    case ACTIVE:
6632        return true;
6633    case IDLE:
6634    case STOPPING:
6635    case STOPPED:
6636    case DESTROYED:
6637    default:
6638        return false;
6639    }
6640}
6641
6642bool AudioFlinger::EffectModule::isProcessEnabled()
6643{
6644    switch (mState) {
6645    case RESTART:
6646    case ACTIVE:
6647    case STOPPING:
6648    case STOPPED:
6649        return true;
6650    case IDLE:
6651    case STARTING:
6652    case DESTROYED:
6653    default:
6654        return false;
6655    }
6656}
6657
6658status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6659{
6660    Mutex::Autolock _l(mLock);
6661    status_t status = NO_ERROR;
6662
6663    // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6664    // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
6665    if (isProcessEnabled() &&
6666            ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6667            (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
6668        status_t cmdStatus;
6669        uint32_t volume[2];
6670        uint32_t *pVolume = NULL;
6671        uint32_t size = sizeof(volume);
6672        volume[0] = *left;
6673        volume[1] = *right;
6674        if (controller) {
6675            pVolume = volume;
6676        }
6677        status = (*mEffectInterface)->command(mEffectInterface,
6678                                              EFFECT_CMD_SET_VOLUME,
6679                                              size,
6680                                              volume,
6681                                              &size,
6682                                              pVolume);
6683        if (controller && status == NO_ERROR && size == sizeof(volume)) {
6684            *left = volume[0];
6685            *right = volume[1];
6686        }
6687    }
6688    return status;
6689}
6690
6691status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6692{
6693    Mutex::Autolock _l(mLock);
6694    status_t status = NO_ERROR;
6695    if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6696        // audio pre processing modules on RecordThread can receive both output and
6697        // input device indication in the same call
6698        uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6699        if (dev) {
6700            status_t cmdStatus;
6701            uint32_t size = sizeof(status_t);
6702
6703            status = (*mEffectInterface)->command(mEffectInterface,
6704                                                  EFFECT_CMD_SET_DEVICE,
6705                                                  sizeof(uint32_t),
6706                                                  &dev,
6707                                                  &size,
6708                                                  &cmdStatus);
6709            if (status == NO_ERROR) {
6710                status = cmdStatus;
6711            }
6712        }
6713        dev = device & AUDIO_DEVICE_IN_ALL;
6714        if (dev) {
6715            status_t cmdStatus;
6716            uint32_t size = sizeof(status_t);
6717
6718            status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6719                                                  EFFECT_CMD_SET_INPUT_DEVICE,
6720                                                  sizeof(uint32_t),
6721                                                  &dev,
6722                                                  &size,
6723                                                  &cmdStatus);
6724            if (status2 == NO_ERROR) {
6725                status2 = cmdStatus;
6726            }
6727            if (status == NO_ERROR) {
6728                status = status2;
6729            }
6730        }
6731    }
6732    return status;
6733}
6734
6735status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
6736{
6737    Mutex::Autolock _l(mLock);
6738    status_t status = NO_ERROR;
6739    if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
6740        status_t cmdStatus;
6741        uint32_t size = sizeof(status_t);
6742        status = (*mEffectInterface)->command(mEffectInterface,
6743                                              EFFECT_CMD_SET_AUDIO_MODE,
6744                                              sizeof(audio_mode_t),
6745                                              &mode,
6746                                              &size,
6747                                              &cmdStatus);
6748        if (status == NO_ERROR) {
6749            status = cmdStatus;
6750        }
6751    }
6752    return status;
6753}
6754
6755void AudioFlinger::EffectModule::setSuspended(bool suspended)
6756{
6757    Mutex::Autolock _l(mLock);
6758    mSuspended = suspended;
6759}
6760
6761bool AudioFlinger::EffectModule::suspended() const
6762{
6763    Mutex::Autolock _l(mLock);
6764    return mSuspended;
6765}
6766
6767status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6768{
6769    const size_t SIZE = 256;
6770    char buffer[SIZE];
6771    String8 result;
6772
6773    snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6774    result.append(buffer);
6775
6776    bool locked = tryLock(mLock);
6777    // failed to lock - AudioFlinger is probably deadlocked
6778    if (!locked) {
6779        result.append("\t\tCould not lock Fx mutex:\n");
6780    }
6781
6782    result.append("\t\tSession Status State Engine:\n");
6783    snprintf(buffer, SIZE, "\t\t%05d   %03d    %03d   0x%08x\n",
6784            mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6785    result.append(buffer);
6786
6787    result.append("\t\tDescriptor:\n");
6788    snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6789            mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6790            mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6791            mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6792    result.append(buffer);
6793    snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6794                mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6795                mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6796                mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6797    result.append(buffer);
6798    snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
6799            mDescriptor.apiVersion,
6800            mDescriptor.flags);
6801    result.append(buffer);
6802    snprintf(buffer, SIZE, "\t\t- name: %s\n",
6803            mDescriptor.name);
6804    result.append(buffer);
6805    snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6806            mDescriptor.implementor);
6807    result.append(buffer);
6808
6809    result.append("\t\t- Input configuration:\n");
6810    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
6811    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
6812            (uint32_t)mConfig.inputCfg.buffer.raw,
6813            mConfig.inputCfg.buffer.frameCount,
6814            mConfig.inputCfg.samplingRate,
6815            mConfig.inputCfg.channels,
6816            mConfig.inputCfg.format);
6817    result.append(buffer);
6818
6819    result.append("\t\t- Output configuration:\n");
6820    result.append("\t\t\tBuffer     Frames  Smp rate Channels Format\n");
6821    snprintf(buffer, SIZE, "\t\t\t0x%08x %05d   %05d    %08x %d\n",
6822            (uint32_t)mConfig.outputCfg.buffer.raw,
6823            mConfig.outputCfg.buffer.frameCount,
6824            mConfig.outputCfg.samplingRate,
6825            mConfig.outputCfg.channels,
6826            mConfig.outputCfg.format);
6827    result.append(buffer);
6828
6829    snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6830    result.append(buffer);
6831    result.append("\t\t\tPid   Priority Ctrl Locked client server\n");
6832    for (size_t i = 0; i < mHandles.size(); ++i) {
6833        sp<EffectHandle> handle = mHandles[i].promote();
6834        if (handle != 0) {
6835            handle->dump(buffer, SIZE);
6836            result.append(buffer);
6837        }
6838    }
6839
6840    result.append("\n");
6841
6842    write(fd, result.string(), result.length());
6843
6844    if (locked) {
6845        mLock.unlock();
6846    }
6847
6848    return NO_ERROR;
6849}
6850
6851// ----------------------------------------------------------------------------
6852//  EffectHandle implementation
6853// ----------------------------------------------------------------------------
6854
6855#undef LOG_TAG
6856#define LOG_TAG "AudioFlinger::EffectHandle"
6857
6858AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6859                                        const sp<AudioFlinger::Client>& client,
6860                                        const sp<IEffectClient>& effectClient,
6861                                        int32_t priority)
6862    : BnEffect(),
6863    mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
6864    mPriority(priority), mHasControl(false), mEnabled(false)
6865{
6866    ALOGV("constructor %p", this);
6867
6868    if (client == 0) {
6869        return;
6870    }
6871    int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6872    mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6873    if (mCblkMemory != 0) {
6874        mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6875
6876        if (mCblk != NULL) {
6877            new(mCblk) effect_param_cblk_t();
6878            mBuffer = (uint8_t *)mCblk + bufOffset;
6879         }
6880    } else {
6881        ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6882        return;
6883    }
6884}
6885
6886AudioFlinger::EffectHandle::~EffectHandle()
6887{
6888    ALOGV("Destructor %p", this);
6889    disconnect(false);
6890    ALOGV("Destructor DONE %p", this);
6891}
6892
6893status_t AudioFlinger::EffectHandle::enable()
6894{
6895    ALOGV("enable %p", this);
6896    if (!mHasControl) return INVALID_OPERATION;
6897    if (mEffect == 0) return DEAD_OBJECT;
6898
6899    if (mEnabled) {
6900        return NO_ERROR;
6901    }
6902
6903    mEnabled = true;
6904
6905    sp<ThreadBase> thread = mEffect->thread().promote();
6906    if (thread != 0) {
6907        thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6908    }
6909
6910    // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6911    if (mEffect->suspended()) {
6912        return NO_ERROR;
6913    }
6914
6915    status_t status = mEffect->setEnabled(true);
6916    if (status != NO_ERROR) {
6917        if (thread != 0) {
6918            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6919        }
6920        mEnabled = false;
6921    }
6922    return status;
6923}
6924
6925status_t AudioFlinger::EffectHandle::disable()
6926{
6927    ALOGV("disable %p", this);
6928    if (!mHasControl) return INVALID_OPERATION;
6929    if (mEffect == 0) return DEAD_OBJECT;
6930
6931    if (!mEnabled) {
6932        return NO_ERROR;
6933    }
6934    mEnabled = false;
6935
6936    if (mEffect->suspended()) {
6937        return NO_ERROR;
6938    }
6939
6940    status_t status = mEffect->setEnabled(false);
6941
6942    sp<ThreadBase> thread = mEffect->thread().promote();
6943    if (thread != 0) {
6944        thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6945    }
6946
6947    return status;
6948}
6949
6950void AudioFlinger::EffectHandle::disconnect()
6951{
6952    disconnect(true);
6953}
6954
6955void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6956{
6957    ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
6958    if (mEffect == 0) {
6959        return;
6960    }
6961    mEffect->disconnect(this, unpiniflast);
6962
6963    if (mHasControl && mEnabled) {
6964        sp<ThreadBase> thread = mEffect->thread().promote();
6965        if (thread != 0) {
6966            thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6967        }
6968    }
6969
6970    // release sp on module => module destructor can be called now
6971    mEffect.clear();
6972    if (mClient != 0) {
6973        if (mCblk != NULL) {
6974            mCblk->~effect_param_cblk_t();   // destroy our shared-structure.
6975        }
6976        mCblkMemory.clear();            // and free the shared memory
6977        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6978        mClient.clear();
6979    }
6980}
6981
6982status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6983                                             uint32_t cmdSize,
6984                                             void *pCmdData,
6985                                             uint32_t *replySize,
6986                                             void *pReplyData)
6987{
6988//    ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6989//              cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
6990
6991    // only get parameter command is permitted for applications not controlling the effect
6992    if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6993        return INVALID_OPERATION;
6994    }
6995    if (mEffect == 0) return DEAD_OBJECT;
6996    if (mClient == 0) return INVALID_OPERATION;
6997
6998    // handle commands that are not forwarded transparently to effect engine
6999    if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7000        // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7001        // no risk to block the whole media server process or mixer threads is we are stuck here
7002        Mutex::Autolock _l(mCblk->lock);
7003        if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7004            mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7005            mCblk->serverIndex = 0;
7006            mCblk->clientIndex = 0;
7007            return BAD_VALUE;
7008        }
7009        status_t status = NO_ERROR;
7010        while (mCblk->serverIndex < mCblk->clientIndex) {
7011            int reply;
7012            uint32_t rsize = sizeof(int);
7013            int *p = (int *)(mBuffer + mCblk->serverIndex);
7014            int size = *p++;
7015            if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
7016                ALOGW("command(): invalid parameter block size");
7017                break;
7018            }
7019            effect_param_t *param = (effect_param_t *)p;
7020            if (param->psize == 0 || param->vsize == 0) {
7021                ALOGW("command(): null parameter or value size");
7022                mCblk->serverIndex += size;
7023                continue;
7024            }
7025            uint32_t psize = sizeof(effect_param_t) +
7026                             ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7027                             param->vsize;
7028            status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7029                                            psize,
7030                                            p,
7031                                            &rsize,
7032                                            &reply);
7033            // stop at first error encountered
7034            if (ret != NO_ERROR) {
7035                status = ret;
7036                *(int *)pReplyData = reply;
7037                break;
7038            } else if (reply != NO_ERROR) {
7039                *(int *)pReplyData = reply;
7040                break;
7041            }
7042            mCblk->serverIndex += size;
7043        }
7044        mCblk->serverIndex = 0;
7045        mCblk->clientIndex = 0;
7046        return status;
7047    } else if (cmdCode == EFFECT_CMD_ENABLE) {
7048        *(int *)pReplyData = NO_ERROR;
7049        return enable();
7050    } else if (cmdCode == EFFECT_CMD_DISABLE) {
7051        *(int *)pReplyData = NO_ERROR;
7052        return disable();
7053    }
7054
7055    return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7056}
7057
7058sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7059    return mCblkMemory;
7060}
7061
7062void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
7063{
7064    ALOGV("setControl %p control %d", this, hasControl);
7065
7066    mHasControl = hasControl;
7067    mEnabled = enabled;
7068
7069    if (signal && mEffectClient != 0) {
7070        mEffectClient->controlStatusChanged(hasControl);
7071    }
7072}
7073
7074void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7075                                                 uint32_t cmdSize,
7076                                                 void *pCmdData,
7077                                                 uint32_t replySize,
7078                                                 void *pReplyData)
7079{
7080    if (mEffectClient != 0) {
7081        mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7082    }
7083}
7084
7085
7086
7087void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7088{
7089    if (mEffectClient != 0) {
7090        mEffectClient->enableStatusChanged(enabled);
7091    }
7092}
7093
7094status_t AudioFlinger::EffectHandle::onTransact(
7095    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7096{
7097    return BnEffect::onTransact(code, data, reply, flags);
7098}
7099
7100
7101void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7102{
7103    bool locked = mCblk != NULL && tryLock(mCblk->lock);
7104
7105    snprintf(buffer, size, "\t\t\t%05d %05d    %01u    %01u      %05u  %05u\n",
7106            (mClient == 0) ? getpid() : mClient->pid(),
7107            mPriority,
7108            mHasControl,
7109            !locked,
7110            mCblk ? mCblk->clientIndex : 0,
7111            mCblk ? mCblk->serverIndex : 0
7112            );
7113
7114    if (locked) {
7115        mCblk->lock.unlock();
7116    }
7117}
7118
7119#undef LOG_TAG
7120#define LOG_TAG "AudioFlinger::EffectChain"
7121
7122AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7123                                        int sessionId)
7124    : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
7125      mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7126      mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
7127{
7128    mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
7129    sp<ThreadBase> thread = mThread.promote();
7130    if (thread == 0) {
7131        return;
7132    }
7133    mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7134                                    thread->frameCount();
7135}
7136
7137AudioFlinger::EffectChain::~EffectChain()
7138{
7139    if (mOwnInBuffer) {
7140        delete mInBuffer;
7141    }
7142
7143}
7144
7145// getEffectFromDesc_l() must be called with ThreadBase::mLock held
7146sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
7147{
7148    sp<EffectModule> effect;
7149    size_t size = mEffects.size();
7150
7151    for (size_t i = 0; i < size; i++) {
7152        if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7153            effect = mEffects[i];
7154            break;
7155        }
7156    }
7157    return effect;
7158}
7159
7160// getEffectFromId_l() must be called with ThreadBase::mLock held
7161sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
7162{
7163    sp<EffectModule> effect;
7164    size_t size = mEffects.size();
7165
7166    for (size_t i = 0; i < size; i++) {
7167        // by convention, return first effect if id provided is 0 (0 is never a valid id)
7168        if (id == 0 || mEffects[i]->id() == id) {
7169            effect = mEffects[i];
7170            break;
7171        }
7172    }
7173    return effect;
7174}
7175
7176// getEffectFromType_l() must be called with ThreadBase::mLock held
7177sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7178        const effect_uuid_t *type)
7179{
7180    sp<EffectModule> effect;
7181    size_t size = mEffects.size();
7182
7183    for (size_t i = 0; i < size; i++) {
7184        if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7185            effect = mEffects[i];
7186            break;
7187        }
7188    }
7189    return effect;
7190}
7191
7192// Must be called with EffectChain::mLock locked
7193void AudioFlinger::EffectChain::process_l()
7194{
7195    sp<ThreadBase> thread = mThread.promote();
7196    if (thread == 0) {
7197        ALOGW("process_l(): cannot promote mixer thread");
7198        return;
7199    }
7200    bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7201            (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
7202    // always process effects unless no more tracks are on the session and the effect tail
7203    // has been rendered
7204    bool doProcess = true;
7205    if (!isGlobalSession) {
7206        bool tracksOnSession = (trackCnt() != 0);
7207
7208        if (!tracksOnSession && mTailBufferCount == 0) {
7209            doProcess = false;
7210        }
7211
7212        if (activeTrackCnt() == 0) {
7213            // if no track is active and the effect tail has not been rendered,
7214            // the input buffer must be cleared here as the mixer process will not do it
7215            if (tracksOnSession || mTailBufferCount > 0) {
7216                size_t numSamples = thread->frameCount() * thread->channelCount();
7217                memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7218                if (mTailBufferCount > 0) {
7219                    mTailBufferCount--;
7220                }
7221            }
7222        }
7223    }
7224
7225    size_t size = mEffects.size();
7226    if (doProcess) {
7227        for (size_t i = 0; i < size; i++) {
7228            mEffects[i]->process();
7229        }
7230    }
7231    for (size_t i = 0; i < size; i++) {
7232        mEffects[i]->updateState();
7233    }
7234}
7235
7236// addEffect_l() must be called with PlaybackThread::mLock held
7237status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
7238{
7239    effect_descriptor_t desc = effect->desc();
7240    uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7241
7242    Mutex::Autolock _l(mLock);
7243    effect->setChain(this);
7244    sp<ThreadBase> thread = mThread.promote();
7245    if (thread == 0) {
7246        return NO_INIT;
7247    }
7248    effect->setThread(thread);
7249
7250    if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7251        // Auxiliary effects are inserted at the beginning of mEffects vector as
7252        // they are processed first and accumulated in chain input buffer
7253        mEffects.insertAt(effect, 0);
7254
7255        // the input buffer for auxiliary effect contains mono samples in
7256        // 32 bit format. This is to avoid saturation in AudoMixer
7257        // accumulation stage. Saturation is done in EffectModule::process() before
7258        // calling the process in effect engine
7259        size_t numSamples = thread->frameCount();
7260        int32_t *buffer = new int32_t[numSamples];
7261        memset(buffer, 0, numSamples * sizeof(int32_t));
7262        effect->setInBuffer((int16_t *)buffer);
7263        // auxiliary effects output samples to chain input buffer for further processing
7264        // by insert effects
7265        effect->setOutBuffer(mInBuffer);
7266    } else {
7267        // Insert effects are inserted at the end of mEffects vector as they are processed
7268        //  after track and auxiliary effects.
7269        // Insert effect order as a function of indicated preference:
7270        //  if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7271        //  another effect is present
7272        //  else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7273        //  last effect claiming first position
7274        //  else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7275        //  first effect claiming last position
7276        //  else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7277        // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7278        // already present
7279
7280        int size = (int)mEffects.size();
7281        int idx_insert = size;
7282        int idx_insert_first = -1;
7283        int idx_insert_last = -1;
7284
7285        for (int i = 0; i < size; i++) {
7286            effect_descriptor_t d = mEffects[i]->desc();
7287            uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7288            uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7289            if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7290                // check invalid effect chaining combinations
7291                if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7292                    iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
7293                    ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
7294                    return INVALID_OPERATION;
7295                }
7296                // remember position of first insert effect and by default
7297                // select this as insert position for new effect
7298                if (idx_insert == size) {
7299                    idx_insert = i;
7300                }
7301                // remember position of last insert effect claiming
7302                // first position
7303                if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7304                    idx_insert_first = i;
7305                }
7306                // remember position of first insert effect claiming
7307                // last position
7308                if (iPref == EFFECT_FLAG_INSERT_LAST &&
7309                    idx_insert_last == -1) {
7310                    idx_insert_last = i;
7311                }
7312            }
7313        }
7314
7315        // modify idx_insert from first position if needed
7316        if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7317            if (idx_insert_last != -1) {
7318                idx_insert = idx_insert_last;
7319            } else {
7320                idx_insert = size;
7321            }
7322        } else {
7323            if (idx_insert_first != -1) {
7324                idx_insert = idx_insert_first + 1;
7325            }
7326        }
7327
7328        // always read samples from chain input buffer
7329        effect->setInBuffer(mInBuffer);
7330
7331        // if last effect in the chain, output samples to chain
7332        // output buffer, otherwise to chain input buffer
7333        if (idx_insert == size) {
7334            if (idx_insert != 0) {
7335                mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7336                mEffects[idx_insert-1]->configure();
7337            }
7338            effect->setOutBuffer(mOutBuffer);
7339        } else {
7340            effect->setOutBuffer(mInBuffer);
7341        }
7342        mEffects.insertAt(effect, idx_insert);
7343
7344        ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
7345    }
7346    effect->configure();
7347    return NO_ERROR;
7348}
7349
7350// removeEffect_l() must be called with PlaybackThread::mLock held
7351size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
7352{
7353    Mutex::Autolock _l(mLock);
7354    int size = (int)mEffects.size();
7355    int i;
7356    uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7357
7358    for (i = 0; i < size; i++) {
7359        if (effect == mEffects[i]) {
7360            // calling stop here will remove pre-processing effect from the audio HAL.
7361            // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7362            // the middle of a read from audio HAL
7363            if (mEffects[i]->state() == EffectModule::ACTIVE ||
7364                    mEffects[i]->state() == EffectModule::STOPPING) {
7365                mEffects[i]->stop();
7366            }
7367            if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7368                delete[] effect->inBuffer();
7369            } else {
7370                if (i == size - 1 && i != 0) {
7371                    mEffects[i - 1]->setOutBuffer(mOutBuffer);
7372                    mEffects[i - 1]->configure();
7373                }
7374            }
7375            mEffects.removeAt(i);
7376            ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
7377            break;
7378        }
7379    }
7380
7381    return mEffects.size();
7382}
7383
7384// setDevice_l() must be called with PlaybackThread::mLock held
7385void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
7386{
7387    size_t size = mEffects.size();
7388    for (size_t i = 0; i < size; i++) {
7389        mEffects[i]->setDevice(device);
7390    }
7391}
7392
7393// setMode_l() must be called with PlaybackThread::mLock held
7394void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
7395{
7396    size_t size = mEffects.size();
7397    for (size_t i = 0; i < size; i++) {
7398        mEffects[i]->setMode(mode);
7399    }
7400}
7401
7402// setVolume_l() must be called with PlaybackThread::mLock held
7403bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
7404{
7405    uint32_t newLeft = *left;
7406    uint32_t newRight = *right;
7407    bool hasControl = false;
7408    int ctrlIdx = -1;
7409    size_t size = mEffects.size();
7410
7411    // first update volume controller
7412    for (size_t i = size; i > 0; i--) {
7413        if (mEffects[i - 1]->isProcessEnabled() &&
7414            (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7415            ctrlIdx = i - 1;
7416            hasControl = true;
7417            break;
7418        }
7419    }
7420
7421    if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
7422        if (hasControl) {
7423            *left = mNewLeftVolume;
7424            *right = mNewRightVolume;
7425        }
7426        return hasControl;
7427    }
7428
7429    mVolumeCtrlIdx = ctrlIdx;
7430    mLeftVolume = newLeft;
7431    mRightVolume = newRight;
7432
7433    // second get volume update from volume controller
7434    if (ctrlIdx >= 0) {
7435        mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
7436        mNewLeftVolume = newLeft;
7437        mNewRightVolume = newRight;
7438    }
7439    // then indicate volume to all other effects in chain.
7440    // Pass altered volume to effects before volume controller
7441    // and requested volume to effects after controller
7442    uint32_t lVol = newLeft;
7443    uint32_t rVol = newRight;
7444
7445    for (size_t i = 0; i < size; i++) {
7446        if ((int)i == ctrlIdx) continue;
7447        // this also works for ctrlIdx == -1 when there is no volume controller
7448        if ((int)i > ctrlIdx) {
7449            lVol = *left;
7450            rVol = *right;
7451        }
7452        mEffects[i]->setVolume(&lVol, &rVol, false);
7453    }
7454    *left = newLeft;
7455    *right = newRight;
7456
7457    return hasControl;
7458}
7459
7460status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7461{
7462    const size_t SIZE = 256;
7463    char buffer[SIZE];
7464    String8 result;
7465
7466    snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7467    result.append(buffer);
7468
7469    bool locked = tryLock(mLock);
7470    // failed to lock - AudioFlinger is probably deadlocked
7471    if (!locked) {
7472        result.append("\tCould not lock mutex:\n");
7473    }
7474
7475    result.append("\tNum fx In buffer   Out buffer   Active tracks:\n");
7476    snprintf(buffer, SIZE, "\t%02d     0x%08x  0x%08x   %d\n",
7477            mEffects.size(),
7478            (uint32_t)mInBuffer,
7479            (uint32_t)mOutBuffer,
7480            mActiveTrackCnt);
7481    result.append(buffer);
7482    write(fd, result.string(), result.size());
7483
7484    for (size_t i = 0; i < mEffects.size(); ++i) {
7485        sp<EffectModule> effect = mEffects[i];
7486        if (effect != 0) {
7487            effect->dump(fd, args);
7488        }
7489    }
7490
7491    if (locked) {
7492        mLock.unlock();
7493    }
7494
7495    return NO_ERROR;
7496}
7497
7498// must be called with ThreadBase::mLock held
7499void AudioFlinger::EffectChain::setEffectSuspended_l(
7500        const effect_uuid_t *type, bool suspend)
7501{
7502    sp<SuspendedEffectDesc> desc;
7503    // use effect type UUID timelow as key as there is no real risk of identical
7504    // timeLow fields among effect type UUIDs.
7505    int index = mSuspendedEffects.indexOfKey(type->timeLow);
7506    if (suspend) {
7507        if (index >= 0) {
7508            desc = mSuspendedEffects.valueAt(index);
7509        } else {
7510            desc = new SuspendedEffectDesc();
7511            memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7512            mSuspendedEffects.add(type->timeLow, desc);
7513            ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
7514        }
7515        if (desc->mRefCount++ == 0) {
7516            sp<EffectModule> effect = getEffectIfEnabled(type);
7517            if (effect != 0) {
7518                desc->mEffect = effect;
7519                effect->setSuspended(true);
7520                effect->setEnabled(false);
7521            }
7522        }
7523    } else {
7524        if (index < 0) {
7525            return;
7526        }
7527        desc = mSuspendedEffects.valueAt(index);
7528        if (desc->mRefCount <= 0) {
7529            ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7530            desc->mRefCount = 1;
7531        }
7532        if (--desc->mRefCount == 0) {
7533            ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7534            if (desc->mEffect != 0) {
7535                sp<EffectModule> effect = desc->mEffect.promote();
7536                if (effect != 0) {
7537                    effect->setSuspended(false);
7538                    sp<EffectHandle> handle = effect->controlHandle();
7539                    if (handle != 0) {
7540                        effect->setEnabled(handle->enabled());
7541                    }
7542                }
7543                desc->mEffect.clear();
7544            }
7545            mSuspendedEffects.removeItemsAt(index);
7546        }
7547    }
7548}
7549
7550// must be called with ThreadBase::mLock held
7551void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7552{
7553    sp<SuspendedEffectDesc> desc;
7554
7555    int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7556    if (suspend) {
7557        if (index >= 0) {
7558            desc = mSuspendedEffects.valueAt(index);
7559        } else {
7560            desc = new SuspendedEffectDesc();
7561            mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
7562            ALOGV("setEffectSuspendedAll_l() add entry for 0");
7563        }
7564        if (desc->mRefCount++ == 0) {
7565            Vector< sp<EffectModule> > effects;
7566            getSuspendEligibleEffects(effects);
7567            for (size_t i = 0; i < effects.size(); i++) {
7568                setEffectSuspended_l(&effects[i]->desc().type, true);
7569            }
7570        }
7571    } else {
7572        if (index < 0) {
7573            return;
7574        }
7575        desc = mSuspendedEffects.valueAt(index);
7576        if (desc->mRefCount <= 0) {
7577            ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7578            desc->mRefCount = 1;
7579        }
7580        if (--desc->mRefCount == 0) {
7581            Vector<const effect_uuid_t *> types;
7582            for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7583                if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7584                    continue;
7585                }
7586                types.add(&mSuspendedEffects.valueAt(i)->mType);
7587            }
7588            for (size_t i = 0; i < types.size(); i++) {
7589                setEffectSuspended_l(types[i], false);
7590            }
7591            ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7592            mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7593        }
7594    }
7595}
7596
7597
7598// The volume effect is used for automated tests only
7599#ifndef OPENSL_ES_H_
7600static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7601                                            { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7602const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7603#endif //OPENSL_ES_H_
7604
7605bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7606{
7607    // auxiliary effects and visualizer are never suspended on output mix
7608    if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7609        (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
7610         (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7611         (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
7612        return false;
7613    }
7614    return true;
7615}
7616
7617void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
7618{
7619    effects.clear();
7620    for (size_t i = 0; i < mEffects.size(); i++) {
7621        if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7622            effects.add(mEffects[i]);
7623        }
7624    }
7625}
7626
7627sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7628                                                            const effect_uuid_t *type)
7629{
7630    sp<EffectModule> effect;
7631    effect = getEffectFromType_l(type);
7632    if (effect != 0 && !effect->isEnabled()) {
7633        effect.clear();
7634    }
7635    return effect;
7636}
7637
7638void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7639                                                            bool enabled)
7640{
7641    int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7642    if (enabled) {
7643        if (index < 0) {
7644            // if the effect is not suspend check if all effects are suspended
7645            index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7646            if (index < 0) {
7647                return;
7648            }
7649            if (!isEffectEligibleForSuspend(effect->desc())) {
7650                return;
7651            }
7652            setEffectSuspended_l(&effect->desc().type, enabled);
7653            index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7654            if (index < 0) {
7655                ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7656                return;
7657            }
7658        }
7659        ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
7660             effect->desc().type.timeLow);
7661        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7662        // if effect is requested to suspended but was not yet enabled, supend it now.
7663        if (desc->mEffect == 0) {
7664            desc->mEffect = effect;
7665            effect->setEnabled(false);
7666            effect->setSuspended(true);
7667        }
7668    } else {
7669        if (index < 0) {
7670            return;
7671        }
7672        ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
7673             effect->desc().type.timeLow);
7674        sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7675        desc->mEffect.clear();
7676        effect->setSuspended(false);
7677    }
7678}
7679
7680#undef LOG_TAG
7681#define LOG_TAG "AudioFlinger"
7682
7683// ----------------------------------------------------------------------------
7684
7685status_t AudioFlinger::onTransact(
7686        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7687{
7688    return BnAudioFlinger::onTransact(code, data, reply, flags);
7689}
7690
7691}; // namespace android
7692