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