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