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