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