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