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