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