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