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