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