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