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