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