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