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