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