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