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